mysql - Sequelize 与同一个表的关联

标签 mysql node.js sequelize.js

我有两个具有以下结构的表:

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/

相关文章:

postgresql - 如何从表中删除已超过 PostgreSQL 过期限制的所有条目?

php - 首次使用后无法创建自动sql表

mysql - MySQL 尝试通过在非索引列上执行 Delete 语句时锁定整个表来防止什么现象

node.js - 使用绝对路径导入组件时,Jest 给出 `Cannot find module`

javascript - 在 Node 中高效地逐行读取文件

sequelize.js - Sequelize - 如何添加/更新插入具有软删除行相同主键的行

node.js - Sequelize 中的返回值到调用方法

mysql - SQL从一部电影中选择参与电影次数较多的 Actor

php - Mysql查询插入多个表相同的id

javascript - node.js - PM2 将未捕获的异常记录到第三方服务(作为 Logentries)