【问题标题】:Sequelize association with one table "hasMany" other tablesSequelize 与一个表“hasMany”其他表的关联
【发布时间】:2017-10-12 00:24:27
【问题描述】:

将同一个表关联到多个表的最佳方法是什么。我在 mysql 数据库中有 3 个表,所有者、宠物、帖子。主人有很多宠物,主人也有很多帖子。当我在 Posts 和 Pets 模型中进行如下关联时

Posts.associate = function(models) {
    Posts.belongsTo(models.Owners, {
        foreignKey: {
            allowNull: false
        }
    });
};
Pets.associate = function(models) {
    Pets.belongsTo(models.Owners, {
        foreignKey: {
            allowNull: false
        }
    });
};

在 Owners 模型中,我尝试建立关联,有很多,对于两者都是这样的:

Owners.associate = function(models) {
    Owners.hasMany(models.Pets, {
      onDelete: "cascade"
    });
};
Owners.associate = function(models) {
    Owners.hasMany(models.Posts, {
      onDelete: "cascade"
    });
};

但我不断收到任何一个表与 Owners 表无关的错误。有没有更好的方法使这种关联发挥作用?

【问题讨论】:

    标签: sequelize.js


    【解决方案1】:

    您只需要在 Owners 模型上使用 hasMany,不需要在其他模型上使用 belongsTo。当您使用 hasMany 时,它会在目标模型上创建 OwnerId,我建议使用 as 这样您就可以识别 如果您需要对查询执行包含,则为关键。此外,您只需定义一次关联函数:

    Owners.associate = function(models) {
      Owners.hasMany(models.Pets, {
        as: 'OwnerPets',
        onDelete: "cascade"
      });
      Owners.hasMany(models.Posts, {
        as: 'OwnerPosts',
        onDelete: "cascade"
      });
    };
    

    【讨论】:

      猜你喜欢
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-23
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多