简体   繁体   中英

how to add extra data with sync method laravel

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

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' ),
    ...
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM