dox19458 2018-04-19 11:10
浏览 137
已采纳

Laravel:SQLSTATE [23000]:完整性约束违规:1452无法添加或更新子行:外键约束失败

I'm using Laravel 5.5. I've my database ready and i have 2 tables. 1) users 2) users_auth_tokens There's no any data filled in users table right now.

So, my requirement is for first time any third user call api to get refreshToken for android device and i will insert data('auth_token', 'refresh_token', 'token_validity') into users_auth_tokens table when it called. There's one field user_id which i want to insert '0' for first time api call and when any user make call api after login, i want to update same record(which is user_id=0) with the logged-in user_id.

But unfortunately, when i was trying to insert record with user_id=0 it's give me error like:

"SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (tracker.users_auth_tokens, CONSTRAINT users_auth_tokens_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into users_auth_tokens (auth_token, validity, refresh_token, updated_at, created_at) values (ETZEI11RY3D7RQE4XR6OBTNQHC6Q1ND187E5FD3E45281D3385D784C3D89C0697D46DDC, 1524135471, b87c88fdcf1eea0a6680620d8da77e4f0ee18b78, 2018-04-19 10:52:51, 2018-04-19 10:52:51))"

I know that why this error occurs because there's foreign key user_id in users_auth_tokens and there's no any record in users table right now! I've tried with default 0 value from migration and make it nullable also, but no luck.

Anyway i want to insert user_id=0 in that table. I search some tricks on google but no one helps.

My code is like:

$usersAuthTokens = new UsersAuthTokens;
$usersAuthTokens->auth_token = $authToken;
$usersAuthTokens->validity = $time;
$usersAuthTokens->refresh_token = $newRefreshToken;
$usersAuthTokens->user_id = 0;  //error is here..because no record in users table right now
$usersAuthTokens->save();

Anyone have an solution for this? Any helps will be appreciated!!

Thanks.

  • 写回答

1条回答 默认 最新

  • dongliechuich10319 2018-04-24 11:14
    关注

    I've fixed it with saving null user_id but not with 0.

    I need to make ->nullable() in migration file and when I am saving the record, I also need to save null value!

    I tried to save user_id=0 but no luck and I've fixed it with null value!

    Thanks for your help @JonasStaudenmeir!

    Hope this will helps any other user in the future if they face the same issue!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化