存储具有多对多关系的相关项目 Laravel

Store related items with many-to-many relationship Laravel

我正在覆盖 voyager 管理面板并尝试在添加新产品表单中存储多个相关项目。 我的观点是

<div class="form-group col-md-8">
   <label class="control-label">Related Products</label>
   <select class="form-control chosen-select">
    @foreach($products as $product)
     <option class="form-control" value="{{$product->id}}" name="related_id[]"> {{$product->name}} </option>
    @endforeach
   </select>
 </div>

产品型号

public function related() {
        return $this->belongsToMany('App\Product', 'related_products', 'product_id', 'related_id');
    }

相关产品型号

class RelatedProduct extends Model
{
    //
    protected $table = 'related_products';
    protected $fillable = ['product_id', 'related_id'];

    public function products() {
        return $this->belongsTo('App\Product', 'related_products', 'product_id', 'related_id');
    }
}

产品负责人

if($data->save()) {
            $productId = $data->id;
            $products = [];
            for ($i=0; $i < $request->related_id; $i++) { 
            
                array_push($products, [
                    'product_id' => $productId,
                    'related_id' => $request->related_id[$i]
                ]);
            }
            

            // Related product pivot table bulk insertion
            RelatedProduct::insert($products);
            
            // response stuff
            return response()->json([
                'success' => true,
                'last_insert_id' => $data->id,
                'related_id'    =>  $request->related_id,
        ], 200);

        }

一切正常,但 related_id 变为空。

尝试更改 loop.Since 你没有提到 related_id 的计数。这可能是原因。

  for ($i=0; $i < count((array)$request->related_id); $i++) {

            array_push($products, [
                'product_id' => $productId,
                'related_id' => $request->related_id[$i]
            ]);
        }

已更新 你也有错误 select

 <select class="form-control chosen-select" name="related_id[]">
    @foreach($products as $product)
     <option class="form-control" value="{{$product->id}}" > {{$product->name}} </option>
    @endforeach
   </select>