[英]How to insert data into a pivot table with columns belonging to same model in Laravel?
我有一個基本上適合被阻止用戶的阻止模型。 它有一個target_id
和sender_id
,它們都是用戶表中的ID。 當用戶想要阻止另一個用戶時,如何向該數據透視表添加數據? 我的關系方法應該是什么樣的?
由於target_id和sender_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']);
}
}
在這里, blocked_users
是表的名稱。
因此,要阻止用戶,您可以執行以下操作:-
//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);
當忽略舊的同步行並附加新的行時,將使用上述同步中的false。
要獲取被該特定用戶阻止的用戶列表,您可以執行以下操作:-
$user = User::find($id);
$user->blocks;
並獲取被該特定用戶阻止的用戶列表
$user = User::find($id);
$user->blockedBy;
謝謝,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.