Laravel 5.8
首先,通过在belongsToMany
后链接withPivot
方法,允许您的枢纽列可搜索。
为了节省时间,这是从我的代码中复制过来的。
// I have 3 columns in my Pivot table which I use in a many-to-many and one-to-many-through scenarios
$task = $user->goalobjectives()->where(['goal_objective_id'=>$goal_objective_id,'goal_obj_add_id'=>$goal_obj_add_id])->first(); //get the first record
$task->pivot->goal_objective_id = $new; //change your col to a new value
$task->pivot->save(); //save
需要注意的是,您的数据透视表需要有一个主键为'id'
。
如果您不想要这个主键,可以尝试以下方法:
$tasks=$user->posts()->where(['posts_id'=>$posts_id,'expires'=>true])->get()->pluck('id');
$key=join(",",array_keys($tasks->toArray(),$valueYouWantToRemove));
$tasks->splice($key,1,$newValueYouWantToInsert);
$c = array_fill(0,$tasks->count(),['expires'=>true]);
$newArray=$tasks->combine($c)
$user->posts()->sync($newArray);
7月4日更新 上述代码片段的更新。
$count = $user->goalobjectives->where('pivot.goal_obj_add_id',$request->record)->count();
if($count) {
$ids = $user->goalobjectives->where('pivot.goal_obj_add_id',$request->record)->pluck('id');
$exists = $ids->toArray();
if(array_sum($inputArray) == array_sum($exists)) {
}
$res = $this->attachToUser($user, $inputArray, $ids, $request->record);
}
elseif(!$count) {
$fill = array_fill(0,count($inputArray),['goal_obj_add_id'=>$request->record]);
$new = array_combine($inputArray,$fill);
$res = $user->goalobjectives()->attach($new);
}
private function attachToUser(User $user, $userData, $storedData, $record) {
$intersect = $storedData->intersect($userData);
if($intersect->count()) {
$extra = collect($userData)->reject(function($value,$key)use($intersect){
return in_array($value,$intersect->toArray());
});
$merge = $intersect->merge($extra);
$recArray = array_fill(0,$merge->count(),['goal_obj_add_id'=>$record]);
$new = $merge->combine($recArray);
$storedArray = $storedData->toArray();
$user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->detach($storedArray);
$res = $user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->syncWithoutDetaching($new);
}
elseif(!$intersect->count()) {
$recArray = array_fill(0,count($userData),['goal_obj_add_id'=>$record]);
$new = $storedData->combine($recArray);
$res = $user->goalobjectives()->wherePivot('goal_obj_add_id',$record)->syncWithoutDetaching($new);
}
return !!$res;
}
如果透视表没有主键自增id,以下方法可以使用。没有自增id,用户无法直接访问透视表来更新、插入或删除任何行。
return $this->hasMany('App\Message\,'message_user','user_id','message_id');
- Mohamed Mo Kawsarareturn $this->belongsToMany('App\Role', 'user_roles', 'user_id', 'role_id');
- Mohamed Mo Kawsara