尝试product_id
从表一中获取,然后将其插入表二,但返回错误
1048列'PRODUCT_ID'不能为空(SQL:INSERT INTO
product_details
(product_id
,category
,brand
,provider_id
)的值(,外设,骑手,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']
]);
可填充产品详细信息模型
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'
at'$product_id = $product->id'
而不是'id'
。向大家道歉。
在插入之前ProductDetails
检查是否Product
已保存。还要检查ProductDetails
模型中的可填写字段是否已添加product_id
。
$product = Product::create([
'product_name' => $request['product_name'],
'quantity' => $request['quantity']
]);
if($product) {
$productDetails = ProductDetails::create([
'product_id' => $product->id,
'category' => $request['category'],
'brand' => $request['brand'],
'provider_id' => $request['provider_id']
]);
}
更新您的可填写字段,如下所示:
protected $fillable = ['product_id', 'category', 'brand', 'provider_id'];
更新
如果您的主键是product_id
,您应该调用$product->product_id
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句