node.js - Sequelize 'reverse' hasOne?

标签 node.js sequelize.js

我正在构建一个应用程序,其中有 3 个主要模型:
诊所、医生、预约
通过 clinic_id 列,医生和约会都属于诊所,因此诊所可以有多个。
一个医生只能属于一个诊所。
每个预约都有一名医生分配给它( doctor_id )
有时我必须通过 id 查询 Appointment,然后我想在查询中查询 include Clinic 和 Doctor,这应该很简单,因为 Apoitment 有 clinic_iddoctor_id
我怎样才能包括那些?我尝试添加 Appointment.hasOne(Doctor, {foreignKey: doctor_id}) 但它然后尝试在 Doctor 上找到 doctor_id 列,而不是在 Appointment 上。
我会尝试 Doctor.belongsTo(Appointment) 但医生实际上属于诊所。
我可以告诉 hasOnedoctor_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/

相关文章:

javascript - 通过 print-html-element npm 库打印时如何防止下载文件?

node.js - 尝试在 Suse 服务器上安装 Angular 时出错

http - 如何很好地销毁 Node.js http.request 连接?

node.js - 带有 Sequelize 的 typescript : UserAdmin.belongsTo 用不是 Sequelize.Model 的子类的东西调用

javascript - 如何在运行时评估 Javascript ES6 代码?

node.js - 在 forEach 之后发送响应

node.js - NodeJS-SequelizeConnectionError : self signed certificate

javascript - 无法获取/mentor/mypage/pre-ordered_Lectures/1

mysql - 子查询同一个表: Sequelize

node.js - 使用数据库进行自动化测试