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!

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

报告相同问题?

悬赏问题

  • ¥500 求华为P30PRO手机硬盘数据恢复
  • ¥15 关于#vscode#的问题:ESP32开发板对接MQTT实现小灯泡的开关
  • ¥15 TMC2209串口模式下读取不到寄存器的值串口助手蓝色字体是发过去的消息,绿色字体是收到的消息,第二行发送读取寄存器的指令但是没有读取到寄存器的值串口助手如下图:接线如下图,如何解决?
  • ¥15 高通安卓11提取完整线刷包软件,或者优博讯dt50顺丰刷机包
  • ¥20 C,有个译码器,换了信道就跑不出原来数据
  • ¥15 MIMIC数据库安装问题
  • ¥60 基于JTag协议开发Fpga下载器上位机,哪位大🐂有偿指导?
  • ¥20 全书网Java爬取数据
  • ¥15 怎么获取红包封面的原始链接,并且获取红包封面序列号
  • ¥100 微信小程序跑脚本授权的问题