2 回答

TA貢獻1829條經驗 獲得超7個贊
你可以使用attach
和detach
方法。
您還可以使用該sync
方法來構造多對多關聯。該sync
方法接受要放置在中間表上的 ID 數組。任何不在給定數組中的 ID 都將從中間表中刪除。因此,此操作完成后,中間表中將只存在給定數組中的 ID:
$user->events()->sync([1,2]);
數組中1,2
是事件 id。
筆記
因為sync, attach
您應該在模型中定義關系。
用戶模型
class User extends Model
{
? ? public function events()
? ? {
? ? ? ? return $this->belongsToMany('App\Event','event_user','user_id','event_id');
? ? }
}
事件模型
class Event extends Model
{
? ? public function users()
? ? {
? ? ? ? return $this->belongsToMany('App\User','event_user','event_id','user_id');
? ? }
}
根據您的代碼。
$user = User::find(Auth::user()->id);
$user->events()->sync([$request->event_id]);

TA貢獻2065條經驗 獲得超14個贊
我的可選答案:
(因為當您有大數據時,附加比同步更快)
//get current synced id
$attachedIds = $user->events()->pluck('id');
//check if there is a new id selected
//if its a single id
$new_id = array_diff([$request->event_id], $attachedIds);
//if its already an array
$new_id = array_diff($request->input('event_id', []), $attachedIds);
$user->events()->attach($new_id);
- 2 回答
- 0 關注
- 268 瀏覽
添加回答
舉報