【问题标题】:Nested include in sequelize?嵌套包含在续集中?
【发布时间】:2016-02-29 17:51:57
【问题描述】:

如何执行嵌套包含? 我有与 cmets 具有一对多关系的表产品,而表 cmets 与 users 表具有多对一关系。 所以 cmets 有 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);
  });
});

我得到了 cmets,但我想要类似的东西

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

如果不编写自定义查询,这可能吗?

【问题讨论】:

    标签: javascript mysql sequelize.js jointable


    【解决方案1】:
    models.products.findAll({
      include: [
        {model: models.comments, include: [models.comments.users] }
      ]
    }) 
    

    【讨论】:

    • 请在您的回答中添加一些解释
    • 这个解决方案不能像写的那样工作(至少在我拥有的版本 3.24.1 中没有)。内部包含应该是 'include: [models.users]'。
    【解决方案2】:

    您可以使用include

    例如:

    Category = sequelize.define(...);
    Product = sequelize.define(...);
    Product.belongsTo(Category, {foreignKey: 'fk_category'});
    
    Product.findAll({
        include: [{
            model: Category
        }]
    });
    

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 这似乎可以编译,但我这边有一个错误:列 X->Y.link 不存在。但我在 X 中有:HasMany Y,在 Y 中有 BelongsTo X。我不明白为什么我不能在 typescript sequelize 中包含这种方式
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多