Laravel for many sync () relationships, where

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

cantains turntable field called id assignment | order_id | worker_id | Appointment

I need to synchronize () when the destination field is reassigned.

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

what does not work.

+1
source share
3 answers

If you have summary variables:

Relations, if you have summary variables:

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

$ array:

$workers[$order_id] = [
    ... // your pivot variables
    'value'         => $value,
    'created_at'    => $created_at,
    'updated_at'    => $updated_at,
]

If you do not have send summary variables and an array of order IDs

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

Edit:

Try with clausule clause in new feature

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

And after:

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

, ( ), wherePivot method

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

use the function withPivotValuein relation to the model as

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


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

and then, as usual, call the function Sync

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

All Articles