Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pass parent id while inserting in 2 columns with one-to-one relation

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading