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?
CodePudding user response:
You should use create()
instead of insert
since it will return a instance of the new Model
that you just created. Then you will use the doctor()
to create a associated to the doctor table.
$newUser = User::create($userData);
$newDoctor = $newUser->doctor()->create($doctorData);
dd($newUser,$newDoctor); //Just to check if the data is inserted.
CodePudding user response:
I think the issue is using ->insert()
; that doesn't perform any kind of linking logic on the associated Model, so user_id
would be null
, as it is not present in $doctorData
.
You can use ->create()
instead:
$newUser = User::create($userData);
$newUser->doctor()->create($doctorData);