首页 > 解决方案 > 续集“反向”hasOne?

问题描述

我正在构建一个应用程序,其中有 3 个主要模型:

诊所, 医生, 预约

医生和约会都通过一列属于诊所clinic_id,因此诊所可以有多个。一名医生只能属于一个诊所。每个预约都有一名医生分配给它(doctor_id

有时我必须通过id查询Appointment,然后我想查询includeClinic和Doctor,这应该很简单,因为Appoitment有clinic_iddoctor_id

我怎样才能包括那些?我尝试添加Appointment.hasOne(Doctor, {foreignKey: doctor_id}),但它随后尝试doctor_id在医生上找到列,而不是在约会上。我会尝试 Doctor.belongsTo(Appointment) 但医生实际上属于诊所。

我可以告诉hasOne寻找模型doctor_id上的列Appointment吗?

标签: node.jssequelize.js

解决方案


您需要使用以下方式定义关联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' })

推荐阅读