[英]filter Sequelize belongsToMany get<Association> association table
[英]sequelize Association with same Table
我有两个具有以下结构的表:
Product
Product.id
Product.name
Product.brand_id
Brand
Brand.id
Brand.name
我要实现的是,对返回具有相同brand_id产品的产品进行关联(或其他操作)。
我的意思是类似Product.other_brand_products []返回产品结果的东西。
我尝试使用VIRTUAL属性来完成此操作,但是由于getter不异步,并且我无法使用where条件(如where:{brand_id:this.brand_id})在这里查询findAll。
是否有可能与最新续集建立这种联系?
感谢您的帮助/想法!
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,因为在这种情况下我真的不需要它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.