php - 流明:一对多插入数据时违反外键约束

标签 php mysql laravel lumen

我正在学习如何插入多对多和一对多的关系。目前,当我尝试创建一个新项目时,我陷入了外键约束。

我的代码非常简单:

$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 has many Articles 关系并且您正尝试插入一个新的 Article,您需要这样做:

$user->articles()->create($request->all()); // Foreign key will be inserted automatically.

或者指定外键:

$this->article->create(array_merge(['user_id' => auth()->id()], $request->all()));

关于php - 流明:一对多插入数据时违反外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46837208/

相关文章:

php - 拉维尔 5.4 : Exclude a route with parameters from CSRF verification

PHP 生成下载文件然后重定向

php - 单击按钮时如何显示文本字段?

php - <> 和 != 有什么区别

php - 单击复选框将显示另一个输入字段,如何将其放入数据库中?

MySQL:如何编写对数字总和求平均值的查询

Laravel 4 Workbench undefined offset

php - Gmail SMTP 问题

mysql order by MIN() where NOT NULL

javascript - 重新加载页面时从变量中删除数据