Laravel many to many relationships sync() where

孤街醉人 提交于 2019-12-24 07:10:32

问题


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


来源:https://stackoverflow.com/questions/37780830/laravel-many-to-many-relationships-sync-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!