[英]Lumen: Foreign key constraint violation when inserting data one to many
我正在學習如何插入多對多和一對多的關系。 目前,當我嘗試創建新項目時,我陷入了外鍵約束。
我的代碼非常簡單:
$this->model->create(
$request->all()
);
請求具有項目 id 並且項目存在的地方。
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails
什么可以解決這個問題?
您需要指定一個外鍵。 例如,如果您有 User 有很多文章關系,並且您嘗試插入新文章,則需要執行以下操作:
$user->articles()->create($request->all()); // Foreign key will be inserted automatically.
或者指定外鍵:
$this->article->create(array_merge(['user_id' => auth()->id()], $request->all()));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.