使用laravel 5.2,我有2个模型叫做命令和工人(多对多关系)
public function workers()
{
return $this->belongsToMany('App\Worker')->withTimestamps();
}
和..
public function orders()
{
return $this->belongsToMany('App\Order')->withTimestamps();
}
数据透视表cantains字段称为赋值 id | order_id | worker_id |分配
我需要sync()重新分配赋值字段。
$order->workers()->where('assignment','Reassigned')->sync($workers);
不起作用..
答案 0 :(得分:1)
不知道它是否有效(暂不测试),但请尝试wherePivot
method
$order->workers()->wherePivot('assignment', 'Reassigned')->sync($workers);
答案 1 :(得分:0)
如果您有透视变量:
如果您有透视变量的关系:
public function workers()
{
return $this->belongsToMany('App\Worker')->withTimestamps()->withPivot('value', 'value2');
}
$ workers array:
$workers[$order_id] = [
... // your pivot variables
'value' => $value,
'created_at' => $created_at,
'updated_at' => $updated_at,
]
如果您没有透视变量发送和订单数组ID
$order->workers()->where('assignment','Reassigned')->sync([1,2,3]);
修改强>
尝试使用新函数中的where clausule
public function workersReassigned()
{
return $this->belongsToMany('App\Worker')->where('assignment','Reassigned')->withTimestamps()->withPivot('value', 'value2');
}
之后:
$order->workersReassigned()->sync($workers);
答案 2 :(得分:0)
在模型关系中使用withPivotValue
函数
喜欢
public function workersReassigned()
{
return $this->belongsToMany('App\Worker')->withPivotValue('assignment','Reassigned');
}
public function workersAnyThingElse()
{
return $this->belongsToMany('App\Worker')->withPivotValue('assignment','AnyThingElse');
}
然后像平常一样调用Sync
函数
$order->workersReassigned()->sync($workers);
$order->workersAnyThingElse()->sync($workers);