node.js - 续集“反向”hasOne?
问题描述
我正在构建一个应用程序,其中有 3 个主要模型:
诊所, 医生, 预约
医生和约会都通过一列属于诊所clinic_id
,因此诊所可以有多个。一名医生只能属于一个诊所。每个预约都有一名医生分配给它(doctor_id
)
有时我必须通过id查询Appointment,然后我想查询include
Clinic和Doctor,这应该很简单,因为Appoitment有clinic_id
和doctor_id
。
我怎样才能包括那些?我尝试添加Appointment.hasOne(Doctor, {foreignKey: doctor_id})
,但它随后尝试doctor_id
在医生上找到列,而不是在约会上。我会尝试 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' })
推荐阅读
- python - pyOpenGL 2D 图像倾斜绘制
- r - 是否有 R 函数来创建 Square 序列
- python-3.x - 如何在 Python 中打印马拉地语字符“”?
- oracle - Apache Kafka 用于使用 Oracle DB 的现有获取请求
- vue.js - 导出变量时如何解决 ESLint 的“首选默认导出”错误?
- javascript - API弹出窗口中的按钮不触发功能,传单路由机
- spark-ar-studio - 在 Spark AR 中,如何根据处于活动状态的摄像头启用不同的自定义指令?
- regex - 如何在 Emacs 的注释中不突出显示值?
- python - 从字典中绘制多个数字
- interface - 无法从派生类中访问接口默认实现方法