嵌套包括在sequelize?

时间:2015-11-26 15:14:48

标签: javascript mysql sequelize.js jointable

如何执行嵌套包含? 我的表产品与注释有一对多的关系,表注释与users表有多对一的关系。 所以评论有user_id和product_id。 我的代码就像这样

var models = require('../models');

models.products.findAll({
    include: [
        {model: models.comments}
    ]
  }).then(function (products) {
    next(products);
  }).catch(function (err) {
    next(err);
  });
});

我收到了评论,但我希望有类似

的内容
models.products.findAll({
    include: [
        {model: models.comments.include(models.comments.users)}
    ]
  }) 

这可以不编写自定义查询吗?

3 个答案:

答案 0 :(得分:10)

models.products.findAll({
  include: [
    {model: models.comments, include: [models.comments.users] }
  ]
}) 

答案 1 :(得分:2)

提供的解决方案对我不起作用,这是我使用的打字稿版本并猜测续集版本:

// sequelize-typescript
models.products.findAll({
  where,
  include: [{
    model: Comment,
    include: [User]
  }]
});

// without typescript (guessing here)
models.products.findAll({
  where,
  include: [{
    model: models.comments,
    include: [{
      model: models.users
    }]
  }]
});

答案 2 :(得分:-1)

您可以使用include

例如:

Category = sequelize.define(...);
Product = sequelize.define(...);
Product.belongsTo(Category, {foreignKey: 'fk_category'});

Product.findAll({
    include: [{
        model: Category
    }]
});

将检索category属性中的嵌套类别,而不仅仅是id。

相关问题