简体   繁体   中英

How can I store two foreign keys from the users table into a second table in Laravel 5.4?

I am stuck as I am new to Laravel.

I have a users table and message table and here is my message table schema

Schema::create('messages', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('sender')->unsigned();
        $table->foreign('sender')->references('id')->on('users')->onDelete('cascade');
        $table->integer('reciever')->unsigned();
        $table->foreign('reciever')->references('id')->on('users')->onDelete('cascade');
        $table->string('msg');
        $table->string('attachment')->nullable();
        $table->string('seen')->default(0);
        $table->integer('deleted')->default(0);
        $table->timestamps();
    });

Here sender and reciever are the both foriegn keys of the user table.

In my app I have access to the sender id from Auth::user() and also I have access to reciever id.. How can I estublish a relationship and store messages? I have been trying in many ways please help. Thank you.

I think my problem is with the relationship. Please have a look and suggest me right way

The User Model

public function sender()
{
   return $this->hasMany('App\Message', 'sender');
}

public function reciever()
{
   return $this->hasMany('App\Message', 'reciever');
}

The Message Model

public function sender()
{
   return $this->belongsTo('App\User', 'sender');
}

public function reciever()
{
   return $this->belongsTo('App\User', 'reciever');
}

You may do it like this:

// Create message model instance
$message = new App\Message(['msg' => 'Something test', ...]);

// Retrieve the related user
$user = App\User::find(1);

// Call the method you defined in user model
$user->sender()->save($message);

Why dont you just store bot sender and receiver ids and when you need to retrieve the data you can use an inner join statement. here is an example of how i did this on my own app

$message->user_id = $userid;
$message->message = $msg;
$message->recipient = "user";

$message->save();

And when retrieving

$msgs = Message::join('users', 'messages.user_id', '=', 'users.id')
        ->select('messages.*', 'users.name', 'users.image')
        ->where('messages.user_id',$id)
        ->get();

In my case i store only one id the other is a string since the messages are always between the admin and users i dont need the admins id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM