【问题标题】:sequelize Association with same Tablesequelize 与同一张表的关联
【发布时间】:2019-03-09 07:53:00
【问题描述】:

我有两个结构如下的表:

Product
Product.id
Product.name
Product.brand_id

Brand
Brand.id
Brand.name

我想要完成的是,在 Product 上有一个关联(或其他),它返回具有相同品牌 ID 的产品。

我的意思是 Product.other_brand_products[] 返回产品结果。

我尝试使用 VIRTUAL 属性来完成此操作,但由于 getter 不是异步的,因此我无法在此处使用 where 条件查询 findAll,例如 where:{ brand_id: this.brand_id }。

是否可以与最新的续集创建这样的关联?

感谢您的帮助/想法!

【问题讨论】:

  • 表示您要退货的产品包括brand_id = this的品牌。品牌标识。对吗?
  • @ChuongTran 是的,这正是我想要实现的目标。
  • 检查我的答案。请

标签: mysql node.js sequelize.js


【解决方案1】:

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);
});

【讨论】:

  • 感谢您的回答伙伴。我所说的更像是这样的: Product.findByPk(1).products_with_same_brand[] 我的意思是,您发布的只是获取具有特定品牌 ID 的产品的简单方法,这不是我真正想要/需要的.也许我的解释不够好。
  • @cham_eleon 意思是same_brand是数组?
【解决方案2】:

我能够在我的产品模型上使用以下 hasMany 关系的定义来完成我想做的事情:

models.product.hasMany(models.product, {
  as: 'brand_products',
  foreignKey: 'brand_id',
  sourceKey: 'brand_id',
  useJunctionTable: false
})

在我的产品模型上,我现在有一个数组 (brand_products[]),我可以访问它来获取具有相同品牌的产品。

解决方案是使用 foreignKey 和 sourceKey 属性以及 useJunctionTable: false 因为在这种情况下我真的不需要它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 2017-10-27
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    相关资源
    最近更新 更多