在Laravel 6中保存多对多关系

时间:2019-12-29 04:11:30

标签: laravel eloquent

我有两个彼此Product的表OrderMany-To-Many。因此,我创建了另一个order_table中间表。

我尝试保存关系many-to-many,但是出现错误unit_price没有默认值。

在产品模型中

    protected $fillable = [
        'name', 'price', 'description', 'status'
    ];

    public function orders()
    {
        return $this->belongsToMany(\App\Order::class);
    }

订购模型中

    protected $fillable = [
        'description', 'ref_no', 'customer_id', 'description', 'active'
    ];


    public function products()
    {
        return $this->belongsTo(\App\Product::class);
    }

并在Order_Product架构中

        Schema::create('order_product', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->unsignedBigInteger('order_id');
            $table->unsignedBigInteger('product_id');
            $table->double('unit_price');
            $table->integer('quantity')->default(1);
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
            $table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
        });

在ProductController中

    public function create(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'price' => 'required',
            'description' => 'nullable',
        ]);

        $product = new Product();
        $product->name = $request->input('name');
        $product->price = $request->input('price');
        $product->status = $request->input('status');
        $product->description = $request->input('description');
        $product->save();

        $orders = new \App\Order();
        $orders->unit_price = $request->unit_price;
        $product->orders()->attach($orders);

        return response()->json(['created' => true]);
    }

感谢您的帮助。...谢谢。...

3 个答案:

答案 0 :(得分:1)

验证数据以确保其存在。

$data = $this->validate($request, [
'unit_price' => 'required|numeric'
]);
$data['unit_price'];

使用get方法并指定一个后备广告

$product->orders()->attach($order, [
'unit_price' => $request->get('unit_price', 0)
]);

一旦解决了问题,就使用“ only”填充枢轴,以便于使用:

$product->orders()->attach(
$order, $request->only(['unit_price'])
);

答案 1 :(得分:0)

尝试

$product->orders()->attach($order, $request->unit_price);

编辑

 $product->orders()->attach($order , ['unit_price' => $request->unit_price]); 

答案 2 :(得分:0)

I got error unit_price doesn't have a default value.

这是数据库问题。请为default value列设置unit_price