我有两个具有以下结构的表:
Product
Product.id
Product.name
Product.brand_id
Brand
Brand.id
Brand.name
我想要实现的是,在Product上拥有一个返回具有相同brand_id的产品的关联(或其他)。
我的意思是像Product.other_brand_products []返回产品结果。
我尝试使用VIRTUAL属性来实现这一点,但由于getter不是异步的,我无法在这里查询findAll,其中where where条件如下:{brand_id:this.brand_id}。
是否有可能与最新的续集创建这样的关联?
感谢您的帮助/想法!
1.检查产品和品牌之间的关联。代码定义如下
Product.associate = function (models) {
// associations can be defined here
Product.belongsTo(models.Brand, {
as: 'brand',
foreignKey: 'brand_id',
targetKey: 'id'
});
};
2.Query
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);
});
我能够通过以下对产品模型的hasMany关系的定义来完成我想要做的事情:
models.product.hasMany(models.product, {
as: 'brand_products',
foreignKey: 'brand_id',
sourceKey: 'brand_id',
useJunctionTable: false
})
在我的产品型号上,我现在有一个阵列(brand_products []),我可以访问该阵列以获得具有相同品牌的产品。
解决方案是使用foreignKey和sourceKey属性以及useJunctionTable:false,因为在这种情况下我真的不需要它。