Laravel many to many relationships sync() where

2019-07-31 16:10发布

问题:

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();
}

and ..

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

the pivot table cantains field called assignment id | order_id | worker_id | assignment

I need to sync() where the assignment field is reassigned ..

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

that does not work ..

回答1:

If you have pivot variables:

Relationship if you have pivot variables:

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,
]

If you don't have pivot variables send and array of orders id's

 $order->workers()->where('assignment','Reassigned')->sync([1,2,3]);

Edit:

Try with the where clausule in a new function

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

And after:

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


回答2:

Don't know will it work or not (not available test it right now), but try wherePivot method

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


回答3:

use withPivotValue function in model relation like

public function workersReassigned()
{
    return $this->belongsToMany('App\Worker')->withPivotValue('assignment','Reassigned');
}


public function workersAnyThingElse()
{
    return $this->belongsToMany('App\Worker')->withPivotValue('assignment','AnyThingElse');
}

and then call Sync function as usual you call it

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