Php SQLSTATE[23000]:完整性约束冲突:1048 laravel
我在尝试将产品附加到订单时遇到以下MYSQL错误: SQLSTATE[23000]:完整性约束冲突:1048列“订单id”不能为空(SQL:插入到Php SQLSTATE[23000]:完整性约束冲突:1048 laravel,php,mysql,laravel,foreign-keys,laravel-5.6,Php,Mysql,Laravel,Foreign Keys,Laravel 5.6,我在尝试将产品附加到订单时遇到以下MYSQL错误: SQLSTATE[23000]:完整性约束冲突:1048列“订单id”不能为空(SQL:插入到订单产品(金额,历史价格,订单id,产品id)值(1,5.35,) 我已经搜索了一个解决方案,但是我找到的所有解决方案似乎都在谈论不使用默认的laravel id作为主键,而我使用的是默认id 以下是三种迁移: Schema::create('orders', function (Blueprint $table) { $table-&
订单产品(金额,历史价格,订单id
,产品id
)值(1,5.35,)
我已经搜索了一个解决方案,但是我找到的所有解决方案似乎都在谈论不使用默认的laravel id作为主键,而我使用的是默认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');
});
这是错误产生的代码:
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约定,我认为没有必要。查看错误消息,值(1,5.35),
,看起来您的$order
和$product
在foreach循环中不可用。如果我理解正确的话。看起来您正在尝试向不允许为NULL的字段添加NULL值$表->整数('order_id')->无符号()。如果希望将null赋值给$table->integer('order_id')->unsigned()->nullable()。@Michael是的,这就是正在发生的事情,但是我希望代码同时添加id和其他信息(它已经是了)。但是,ID是missing@ItaiNathaniel这可能是可能的,但对我来说似乎不太可能,因为可以从$order变量调用products()关系。所以看起来至少订单应该是可用的。正如@Itai Nathaniel提到的,在您的foreach中只有get(['price','amount'])。“订单id”=>$order->id,“产品id”=>$product->id从何处开始?来自您能否反向跟踪现有值的路径?
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();