Laravel 多对多关系 sync() 其中

Laravel many to many relationships sync() where

with laravel 5.2,我有 2 个模型,分别是 order 和 worker(多对多关系)

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

和..

    public function orders()
{
    return $this->belongsToMany('App\Order')->withTimestamps();
}

主元 table 包含名为赋值的字段 编号 | order_id | worker_id |作业

我需要在重新分配分配字段的地方同步()..

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

那行不通..

如果你有主变量:

关系如果你有主变量:

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

编辑:

尝试在新函数中使用 where 子句

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

之后:

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

不知道它是否有效(现在无法测试),但请尝试 wherePivot method

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

在模型关系中使用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);