1

I have next structure pivot table: products_equipment_value(id, product_id, equipment_id, value_id).How to update table fields equipment_id and value_id ?

 public function equipments()
    {
        return $this->belongsToMany('App\Equipment', ' product_equipment_value');
    }

    public function values()
    {
        return $this->belongsToMany('App\Value', ' product_equipment_value', 'product_id', 'value_id')
    }

Use(not work)

 $product->equipments()->detach();
       foreach($data['eq'] as $key => $val){
         $product->equipments()->attach([
           'equipment_id' =>  $key,
            'value_id' =>$val
          ]);
      }
Marco Roys
  • 171
  • 3
  • 14

2 Answers2

1

You should use withPivot function on the relations.

public function equipments()
{
    return $this->belongsToMany('App\Equipment', 'product_equipment_value')->withPivot('value_id');
}

Then when you attach the models

$product->equipments()
    ->attach([
        $key => ['value_id' =>$val],            
    ]);
Aboudeh87
  • 716
  • 5
  • 16
  • And how to deduce Product (simple method) |product.title|equipment.title|value.title| – Marco Roys Sep 18 '17 at 10:41
  • When you call $product->equipments will return a collection of equipments if you want only first one use first() method ($product->equipments->first()->title) – Aboudeh87 Sep 18 '17 at 22:17
1

Referring to Many to Many Eloquent's relationship (https://laravel.com/docs/5.5/eloquent-relationships#many-to-many) you can sync IDs like this :

$product->equipments()->sync([array_of_equipments_ids]);

Example:

$product->equipments()->sync([3, 8, 9, 24]);

If you defined the Many to Many inverse relationship you can also do this that way from the equipment instance :

$equipment->values()->sync([array_of_values_ids]);

If you have extra columns with your pivot table you can add them like this :

public function equipments(){
    return $this->belongsToMany('App\Equipment', 'product_equipment_value')->withPivot('extra_column1');
}

And so :

$product->equipments()->sync([1 => ['extra_column1' => 'Value for this column']])

Note that you can use sync() or attach() methods to construct many-to-many associations. You can take a look here : https://stackoverflow.com/a/23969879/8620746

ThomasRift
  • 98
  • 6