【发布时间】:2019-03-09 05:16:50
【问题描述】:
试图从表一中获取product_id,然后将其插入表二,但返回错误
1048 列“product_id”不能为空(SQL:插入
product_details(product_id、category、brand、provider_id)值(外设、Riders、1))
代码:
$product = Product::create([
'product_name' => $request['product_name'],
'quantity' => $request['quantity']
]);
$product->save();
$product_id = $product->id;
$productDetails = ProductDetails::create([
'product_id' => $product_id,
'category' => $request['category'],
'brand' => $request['brand'],
'provider_id' => $request['provider_id']
]);
可填写productdetails型号
protected $fillable = ['product_id', 'category', 'brand', 'provider_id'];
数据库结构:(记起来了,前段时间我对数据库做了一些改动,就是这个错误出现的时候。)
产品:
Schema::create('products', function (Blueprint $table) {
$table->increments('product_id');
$table->string('product_name');
$table->integer('quantity');
产品详情:
Schema::create('product_details', function (Blueprint $table) {
$table->integer('product_id')->unsigned();
$table->string('category',255);
$table->string('brand',255);
$table->integer('provider_id')->unsigned();
$table->foreign('product_id')
->references('product_id')
->on('products')
->onDelete('cascade');
$table->timestamps();
});
已经解决了,
这只是我的一个简单错误。我应该在'$product_id = $product->id' 上使用'product_id' 而不是'id'。向大家道歉。
【问题讨论】:
-
这个
dd($product_id);的输出是什么? -
并显示 ProductDetails 模型的 fillable 属性
-
@InzamamIdrees 输出产品的 id。
-
你的id生成了吗?
-
product_id 是自动递增的,所以是的