简体   繁体   中英

How to insert data into a pivot table with columns belonging to same model in Laravel?

I have a Block model which is basically for blocked users. It has a target_id and a sender_id , both of which are IDs from the users table. How can I add data to this pivot table when a user wants to block another user? What should my relationship methods look like?

Since both target_id and sender_id are fields from the users table, your relationship must be defined this way.

class User {

  public function blocks() {
    return $this->belongsToMany('App\User','blocked_users','sender_id','target_id')->withPivot(['id']);
   }

  public function blockedBy() {
    return $this->belongsToMany('App\User','blocked_users','target_id','sender_id')->withPivot(['id']);
   }

}

Here blocked_users is the name of the table.

So, to block a user you can do :-

//User who is going to block
$user = User::find($id);
$inputs = [$target_user_id];
$user->blocks()->attach($inputs);

//or you can use,
$user->blocks()->sync($inputs, false);

The false in the above sync is used when the old synced rows are ignored and new ones are attached.

To get the list of users who that particular user has blocked, you can do :-

$user = User::find($id);
$user->blocks;

And to get the list of users who that particular user is blocked by

$user = User::find($id);
$user->blockedBy;

Thanks,

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