首页 > 解决方案 > Laravel / Eloquent - 如何在 updateExistingPivot() 调用中添加额外的 wherePivot() 条件?

问题描述

我有一个包含以下列的参考表:

-user_id (foreign key)
-location_id (foreign key)
-skill_level
-court_id

我可以更新skill_level上表中的数据透视列值:

$user = User::find($user_id)
$user->locations()->updateExistingPivot($location_id, array(
    'skill_level' => $new_value
));

我想添加类似于wherePivot()上述内容的内容,以便仅更新与某个court_id(除了user_idand之外location_id)匹配的记录。类似于:

->wherePivot('court_id', '=', $court_id);

我将如何通过updateExistingPivot()电话做到这一点?

标签: laravellaravel-5eloquentlaravel-5.2

解决方案


我最终使用了newPivotStatement()- 它允许您从数据透视表中启动一系列语句。

而不是 using updateExistingPivot(),调用看起来像:

$user->locations()->newPivotStatement()->where('location_id', '=', $location_id)  
     ->where('court_id', '=', $court_id)->update(array(
    'skill_level' => $new_value
));

推荐阅读