SQLSTATE [23000]:完整性约束违规:1048 laravel

时间:2018-06-10 09:00:03

标签: php mysql laravel foreign-keys laravel-5.6

我在尝试将产品附加到订单时遇到以下MYSQL错误:

  

SQLSTATE [23000]:完整性约束违规:1048列'order_id'不能为空(SQL:插入order_productamounthistory_priceorder_id,{ {1}})值(1,5.35 ,,))

我已经搜索了一个解决方案,但是我设法找到的所有解决方案似乎都没有使用默认的laravel id作为主键,而我使用的是默认ID。

以下是三次迁移:

product_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'));
    });

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

0 个答案:

没有答案