两个不同外键列的同一个表的外键关系

问题描述 投票:3回答:2

假设我有一个用户和约会表。

用户 - 身份证,姓名,电子邮件,类型(医生/病人)

预约ID,医生user_id,患者user_id

我的用户表数据 -

enter image description here

我的预约表数据 -

enter image description here

我可以让两个属于与用户表约会的关系。

正如您可以看到我的约会表,我想只将该类型为doctor的用户存储到doctor_user_id,将患者存储到patient_user_id。但在这种情况下,我可以将任何用户ID添加到doctor_user_id字段,无论是医生还是患者,但我只想添加用户ID作为doctor_user_id,只要其类型是医生。

我知道如何使用两个不同的表来实现这一点,但我想知道有没有办法用单用户表来实现这一点,谢谢。

php mysql sql laravel
2个回答
3
投票

是的,您可以通过仅创建一个用户表来实现此目的。

为参考User表的约会表的“doctor_user_id”和“patient_user_id”创建2个外键。


3
投票

您可以使用两个belongsToMany()关系并使用该表作为我的枢轴:

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');
}

如果你将大量使用appointment表,你还可以为hasMany()模型添加两个Appointment关系,并为belongsTo()模型添加两个User关系。因此,在这种情况下,您可以同时使用belongsToMany()hasMany()belongsTo()关系。

© www.soinside.com 2019 - 2024. All rights reserved.