SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails - Laravel

空扰寡人 提交于 2019-12-05 04:58:10

A user row needs a reference to a valid location. That location must be available before the user is saved. So, first save the location and then save the user and uncomment the $user->location_id line and you are done.

Kaleemullah

Those Developers who face this error:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (laravel.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)
(SQL: insert into articles (title, user_id, body, updated_at, created_at) values (rao, 1, sflkkjk, 2016-03-01 20:45:32, 2016-03-01 20:45:32))
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row:
a foreign key constraint fails (laravel.articles, CONSTRAINT articles_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE)
(SQL: insert into articles (title, user_id, body, updated_at, created_at) values (rao, 1, sflkkjk, 2016-03-01 20:45:32, 2016-03-01 20:45:32))

First Save the user record of user then try to insert record then easily inserted into the database.

KEY POINT

Two Tables: one is article and other is user. A user has many articles but no article has many users. So foreign key is shifted toward the article table. If user table has no record then you face the same error seen earlier.

By doing this we can easily solve this issue.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!