简体   繁体   中英

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

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM