嵌套包括在sequelize?

iho*_*yam 6 javascript mysql jointable sequelize.js

如何执行嵌套包含?我的表产品与注释有一对多的关系,表注释与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);
  });
});
Run Code Online (Sandbox Code Playgroud)

我得到了评论,但我想有类似的东西

models.products.findAll({
    include: [
        {model: models.comments.include(models.comments.users)}
    ]
  }) 
Run Code Online (Sandbox Code Playgroud)

没有编写自定义查询,这可能吗?

Que*_*n C 12

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

// 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
    }]
  }]
});
Run Code Online (Sandbox Code Playgroud)


Jan*_*ier 10

models.products.findAll({
  include: [
    {model: models.comments, include: [models.comments.users] }
  ]
}) 
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案无法正常工作(至少在我的版本中没有,3.24.1).内部包含应该是'include:[models.users]'. (5认同)
  • 请为您的答案添加一些解释 (2认同)

小智 5

有一个非常简单又简洁的方法!https://sequelize.org/docs/v6/advanced-association-concepts/eager-loading/#include-everything

// Fetch all models associated with User
User.findAll({ include: { all: true }});

// Fetch all models associated with User and their nested associations (recursively) 
User.findAll({ include: { all: true, nested: true }});
Run Code Online (Sandbox Code Playgroud)