sqlstate[23000]:完整性约束冲突:1048 laravel

ego6inou  于 2021-06-21  发布在  Mysql
关注(0)|答案(0)|浏览(434)

尝试将产品附加到订单时出现以下mysql错误:
sqlstate[23000]:完整性约束冲突:1048列“order\u id”不能为null(sql:insert into) order_product ( amount , history_price , order_id , product_id )数值(1,5.35,)
我已经搜索了一个解决方案,但是我找到的所有解决方案似乎都在谈论不使用默认的laravelid作为主键,而我使用的是默认的id。
以下是三种迁移:

Schema::create('orders', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->integer('status_id')->unsigned();
        $table->boolean('visible')->default(true);
        $table->string('postal_code');
        //$table->string('country');
        $table->string('municipality');
        $table->string('street');
        $table->string('house_number');

        $table->timestamps();
    });

    Schema::table('orders', function($table) {
        $table->foreign('user_id')
            ->references('id')
            ->on('users')
            ->onDelete('cascade');

        $table->foreign('status_id')
            ->references('id')
            ->on('statuses')
            ->onDelete('cascade');
    });
Schema::create('products', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('name', 100);
        $table->float('price');
        $table->integer('stock');
        $table->string('short_description', 240);
        $table->string('long_description', 1000);
        $table->boolean('visible')->default(true);
        $table->string('image_url',240);
        $table->timestamps();
    });
Schema::create('order_product', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('order_id')->unsigned();
        $table->integer('product_id')->unsigned();
        $table->float('history_price');
        $table->integer('amount');
        $table->timestamps();
    });

    Schema::table('order_product', function($table) {
        $table->foreign('order_id')
            ->references('id')
            ->on('orders')
            ->onDelete('cascade');

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

        $table->primary(array('order_id', 'product_id'));
    });

这是错误产生的代码:

foreach($user->products()->get(['price','amount']) as $product){
        $order->products()->attach($product, array('history_price'=> $product->price, 'amount'=>$product->amount,'order_id'=>$order->id, 'product_id'=>$product->id));
}
$order->save();

如果需要,我可以提供模型方法来定义两者之间的关系,但是由于这些表遵循标准的laravel约定,我认为没有必要。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题