2017-10-11 55 views
0

将同一个表与多个表相关联的最佳方式是什么?我在MySQL数据库中有3个表,Owners,Pets,Posts。业主有很多宠物,业主也有很多帖子。当我做的文章和宠物模型的关联如下将一个表与“hasMany”其他表相关联

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

而在业主模型我试图让联想,有很多,对于这样的:

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

,但我一直在获取错误,其中一个表中没有关联到Owners表。有没有更好的方式使这种关联起作用?

回答

0

您只需在拥有者模型上使用hasMany,不需要在其他模型上使用belongsTo。当您使用hasMany时,它会在目标模型上创建OwnerId,我建议使用as,因此如果您需要在查询上执行Include,您可以识别 密钥。你也可以定义一次关联功能:

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

好的谢谢!会尝试。 –

相关问题