I have 2 columns with one-to-one relation users
and doctors
:
Users
_____________
| id | name |
|____|______|
| 1 | John |
|____|______|
Doctors
_____________________
| id | dep | user_id |
|____|_____|_________|
| 1 | 2 | 1 |
|____|_____|_________|
User
model has this function that returns the doctor with relation:
public function doctor(){
return $this->hasOne(Doctor::class);
}
Inserting data:
$valdiated = $request->validated();
$userData = [
'name' => $valdiated['name'],
];
$doctorData = [
'dep' => $valdiated['dep'],
];
$newUser = new User();
$newUser->insert($userData);
$newUser->doctor()->insert($doctorData);
But I’m getting this error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`db`.`doctors`, CONSTRAINT `doctors_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into `doctors` (`dep`) values (2))
Is there a way to insert the user_id
into doctors
table or I have to query the database and get the last id?
2
Answers
You should use
create()
instead ofinsert
since it will return a instance of the newModel
that you just created. Then you will use thedoctor()
to create a associated to the doctor table.I think the issue is using
->insert()
; that doesn’t perform any kind of linking logic on the associated Model, souser_id
would benull
, as it is not present in$doctorData
.You can use
->create()
instead: