如何使用Sequelize for Postgresql在Express中实现IS-A关系?

我希望实现IS-A关系。我读过https://sequelize.org/master/manual/associations.html#one-to-one-associations并认为应该使用一个属于关系。例如,假设我有一位IS-A Doctor的骨科医师。这是正确的方法吗?

Orthopedic.belongsTo(models.Doctor,{
    name: 'id',type: DataTypes.INTEGER,primaryKey: true
 });

模型:

module.exports = (sequelize,DataTypes) => {
    const Orthopedic = sequelize.define('Orthopedic',{
        specialization: {
            type: DataTypes.STRING,},});


    return Orthopedic;
};

module.exports = (sequelize,DataTypes) => {
    const Doctor = sequelize.define('Doctor',{
        name: {
            type: DataTypes.STRING,age: {
            type: DataTypes.INTEGER,});


    return Doctor;
};

m13432900836 回答:如何使用Sequelize for Postgresql在Express中实现IS-A关系?

belongsTo关联化文档:

  

BelongsTo关联是源模型上存在一对一关系的外键的关联。

     

一个简单的例子是,一名玩家加入了团队,并在其上拥有外键。

class Player extends Model {}
Player.init({/* attributes */},{ sequelize,modelName: 'player' });
class Team extends Model {}
Team.init({/* attributes */},modelName: 'team' });

Player.belongsTo(Team); // Will add a teamId attribute to Player to hold the primary key value for Team

根据您的情况,您需要添加

Orthopedic.belongsTo(models.Doctor)

请注意,这会将doctorId属性添加到Orthopedic模型中,该属性未在原始模型定义中定义。

此建议与您的原始建议之间的区别在于,options参数与关联相关,并且不应定义模型的属性。

本文链接:https://www.f2er.com/3141999.html

大家都在问