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 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题