假设我有一个用户和约会表。
用户 - 身份证,姓名,电子邮件,类型(医生/病人)
预约ID,医生user_id,患者user_id
我的用户表数据 -
我的预约表数据 -
我可以让两个属于与用户表约会的关系。
正如您可以看到我的约会表,我想只将该类型为doctor的用户存储到doctor_user_id,将患者存储到patient_user_id。但在这种情况下,我可以将任何用户ID添加到doctor_user_id字段,无论是医生还是患者,但我只想添加用户ID作为doctor_user_id,只要其类型是医生。
我知道如何使用两个不同的表来实现这一点,但我想知道有没有办法用单用户表来实现这一点,谢谢。
是的,您可以通过仅创建一个用户表来实现此目的。
为参考User表的约会表的“doctor_user_id”和“patient_user_id”创建2个外键。
您可以使用两个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()
关系。