2

I am using Laravel and I have three tables: products, features, and feature_product that third table has one extra column "value" that I want add value of each feature while syncing

so sync method is working without value but whenever I want to send value it gives me error

here is my code

  if($request->get('feature')){
      foreach($request->get('feature') as $featureName)
      {
          $feature = Feature::find($featureName);
          if($feature)
          {
            $featureIds[] = $feature->id;
          }
      }

      $product->features()->sync($featureIds);
    }

here is my error

General error: 1364 Field 'value' doesn't have a default value (SQL: insert into feature_product (feature_id, product_id) values (11, 99))

I konw this is because I did not send value for that , I want to know How can I do this

hassan khosro
  • 149
  • 1
  • 16

1 Answers1

2

You're missing pivot value in sync that why you're getting this error.

if($request->get('feature')){
    $featureIds = array();
    foreach($request->get('feature') as $featureName)
    {
      $feature = Feature::find($featureName);

      if($feature){
        $featureIds[$feature->id] = ['value'=>'yourvalue'];
      }
    }

    $product->features()->sync($featureIds);
}

Try to make this kinda array to sync.

$product->features()->sync( array( 
    1 => array( 'value' => 'xyz' ),
    2 => array( 'value' => 'abc' ),
    ...
));
Dilip Hirapara
  • 14,810
  • 3
  • 27
  • 49