[英]1452 Cannot add or update a child row: a foreign key constraint fails
I get this error when creating a new product. 创建新产品时出现此错误。 This is the function: 这是功能:
public function createProduct(Request $request) {
$product = Product::create($request->all());
$product->title = strip_tags($request->title);
$product->description = strip_tags($request->description);
$product->price = strip_tags($request->price);
$product->category_id = 1;
$product->save();
return redirect('/');
}
'insert into products
( title
, description
, price
, image
, updated_at
, created_at
) values (?, ?, ?, ?, ?, ?) '插入products
( title
, description
, price
, image
, updated_at
, created_at
)值(?,?,?,?,?,?)
But why I can't see category_id
between these values ? 但为什么我看不到这些值之间的category_id
? I also made category_id
fillable in Product.php 我还在Product.php category_id
填写了category_id
protected $fillable = [
'slug', 'title', 'description', 'stock', 'price', 'image',
'category_id'
];
And I've also created category
in categories
table with an ID of 1 而且我还创建category
在categories
表为1的ID
Can someone help ? 有人可以帮忙吗?
Your problem is you create and save the model before you set the category_id. 您的问题是在设置category_id之前创建并保存模型。 Your request data must not have a category ID. 您的请求数据不得包含类别ID。
$product = Product::create($request->all());
This will attempt to insert the row (create+save the model) into the database using the data you pass to it. 这将尝试使用您传递给它的数据将行(创建+保存模型)插入数据库。
So by the time you hit: 所以当你点击时:
$product->title = strip_tags($request->title);
Your insert query has already been sent. 您的插入查询已发送。 For readability sake, don't mix create or make with setters. 为了便于阅读,请不要将set或make与setter混合使用。 Either do: 要么:
$product = Product::create([
'category_id' => 1,
...
]);
Or do: 或者做:
$product = new Product();
$product->category_id = 1;
...
$product->save();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.