Laravel多对多关系sync()其中 [英] Laravel many to many relationships sync() where
本文介绍了Laravel多对多关系sync()其中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用laravel 5.2时,我有2个称为订单"和工作者"(多对多关系)的模型
with laravel 5.2,I have 2 models called order and worker (Many to Many relationship)
public function workers()
{
return $this->belongsToMany('App\Worker')->withTimestamps();
}
和..
public function orders()
{
return $this->belongsToMany('App\Order')->withTimestamps();
}
数据透视表可以包含称为赋值的字段 id | order_id | worker_id |作业
the pivot table cantains field called assignment id | order_id | worker_id | assignment
我需要在分配字段重新分配的位置进行sync().
I need to sync() where the assignment field is reassigned ..
$order->workers()->where('assignment','Reassigned')->sync($workers);
那是行不通的..
推荐答案
如果您有数据透视变量:
关系,如果您有数据透视变量:
Relationship if you have pivot variables:
public function workers()
{
return $this->belongsToMany('App\Worker')->withTimestamps()->withPivot('value', 'value2');
}
$ workers数组:
$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子句
Try with the where clausule in a new function
public function workersReassigned()
{
return $this->belongsToMany('App\Worker')->where('assignment','Reassigned')->withTimestamps()->withPivot('value', 'value2');
}
及之后:
$order->workersReassigned()->sync($workers);
这篇关于Laravel多对多关系sync()其中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文