![](/img/trans.png)
[英]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.