【问题标题】:Sequelize 'reverse' hasOne?续集“反向”hasOne?
【发布时间】:2021-03-11 04:42:02
【问题描述】:

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

诊所、医生、预约

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

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

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

我可以告诉hasOneAppointment 模型上查找doctor_id 列吗?

【问题讨论】:

  • “我会尝试 Doctor.belongsTo(Appointment) 但医生实际上属于诊所”——模型可以属于多个模型。

标签: node.js sequelize.js


【解决方案1】:

您需要使用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' })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-05
    • 2017-10-20
    • 2017-09-06
    • 2014-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多