我有两个具有以下结构的表:
Product
Product.id
Product.name
Product.brand_id
Brand
Brand.id
Brand.name
我想要完成的是,在产品上建立一个关联(或其他),返回具有相同品牌 ID 的产品。
我的意思是 Product.other_brand_products[] 返回产品结果。
我尝试使用 VIRTUAL 属性来实现此目的,但由于 getter 不是异步的,因此我无法使用 where 条件(例如 where: {brand_id: this.brand_id })在此处查询 findAll。
是否可以与最新的 Sequelize 创建这样的关联?
感谢您的帮助/想法!
最佳答案
1.检查产品与品牌之间的关联。代码定义如下
Product.associate = function (models) {
// associations can be defined here
Product.belongsTo(models.Brand, {
as: 'brand',
foreignKey: 'brand_id',
targetKey: 'id'
});
};
2.查询
var brand_id = 1;
Product.findAll({
where: {
brand_id: brand_id
},
include: [{
model: Brand,
as: 'brand',
attributes: ['id', 'name'],
}]
})
.then(products => {
})
.catch(err => {
console.log('err', err);
});
关于mysql - Sequelize 与同一个表的关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55075190/