简体   繁体   English

如何在Laravel中将数据插入具有相同模型列的数据透视表中?

[英]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. 它有一个target_idsender_id ,它们都是用户表中的ID。 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. 由于target_idsender_id都是users表中的字段,因此必须以这种方式定义您的关系。

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. 在这里, blocked_users是表的名称。

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. 当忽略旧的同步行并附加新的行时,将使用上述同步中的false。

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, 谢谢,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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