Laravel多对多关系同步(),其中(Laravel many to many relations

2019-09-27 14:39发布

与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 | 分配

我需要同步()在分配领域重新分配..

            $order->workers()->where('assignment','Reassigned')->sync($workers);

不工作..

Answer 1:

如果你有支点变量:

关系,如果你有支点变量:

public function workers()
{
    return $this->belongsToMany('App\Worker')->withTimestamps()->withPivot('value', 'value2');
}

美元的劳动者阵:

$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]);

编辑:

与其中clausule尝试在新功能

public function workersReassigned()
{
    return $this->belongsToMany('App\Worker')->where('assignment','Reassigned')->withTimestamps()->withPivot('value', 'value2');
}

之后:

 $order->workersReassigned()->sync($workers);


Answer 2:

不知道将它的工作或没有(不能测试它现在),但尝试wherePivot 方法

 $order->workers()->wherePivot('assignment', 'Reassigned')->sync($workers);


Answer 3:

使用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);


文章来源: Laravel many to many relationships sync() where