我正在构建一个应用程序,其中有 3 个主要模型:
诊所、医生、预约
通过 clinic_id
列,医生和约会都属于诊所,因此诊所可以有多个。
一个医生只能属于一个诊所。
每个预约都有一名医生分配给它( doctor_id
)
有时我必须通过 id 查询 Appointment,然后我想在查询中查询 include
Clinic 和 Doctor,这应该很简单,因为 Apoitment 有 clinic_id
和 doctor_id
。
我怎样才能包括那些?我尝试添加 Appointment.hasOne(Doctor, {foreignKey: doctor_id})
但它然后尝试在 Doctor 上找到 doctor_id
列,而不是在 Appointment 上。
我会尝试 Doctor.belongsTo(Appointment) 但医生实际上属于诊所。
我可以告诉 hasOne
在 doctor_id
模型上查找 Appointment
列吗?
最佳答案
您需要使用 belongsTo
定义关联:
Appointment.belongsTo(Doctor, { foreignKey: 'doctor_id' })
Appointment.belongsTo(Clinic, { foreignKey: 'clinic_id' })
根据您对模型的描述,Clinic
- Doctor
为 1:N,Clinic
- Appointment
为 1:N,Appointment
- Doctor
为 N:1。所有其他关联应如下所示:
Doctor.belongsTo(Clinic, { foreignKey: 'clinic_id' })
Doctor.hasMany(Appointment, { foreignKey: 'doctor_id' })
Clinic.hasMany(Appointment, { foreignKey: 'clinic_id' })
Clinic.hasMany(Doctor, { foreignKey: 'clinic_id' })
关于node.js - Sequelize 'reverse' hasOne?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65053591/