简体   繁体   中英

Foreign key relationships with the same table for two different foreign key columns

Lets say I have a user and appointment table.

users - id, name, email, type(doctor/patient)

appointment - id, doctor_user_id, patient_user_id

My user table data-

在此输入图像描述

And my appointment table data-

在此输入图像描述

I could make two belongs to relationships from appointment with user table.

As you can see my appointment table, I want to store only user that type is doctor to doctor_user_id and patient to patient_user_id . But in this case i can add any user id to doctor_user_id field either it is doctor or patient but i want to add only user id as doctor_user_id only if its type is doctor.

I know how to achieve this with two different table but I was wondering is there any way to achieve this with single user table, Thanks.

Yes, you can achieve this by creating one user table only.

Create 2 foreign key for the "doctor_user_id" and "patient_user_id" of appointment table which references to User table.

You can use two belongsToMany() relationships and use the table as I pivot:

public function doctors()
{
    return $this->belongsToMany(User::class, 'appointment', 'patient_user_id', 'doctor_user_id');
}

public function patients()
{
    return $this->belongsToMany(User::class, 'appointment', 'doctor_user_id', 'patient_user_id');
}

If you'll use the appointment table a lot, you can also add two hasMany() relationships to the Appointment model and two belongsTo() relationships to the User model. So, you could use belongsToMany() , hasMany() and belongsTo() relationships simultaneously for in this case.

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