【问题标题】:Sequelize: query to include a parent model's data if it has associated children; don't return the child model's dataSequelize:查询是否包含父模型的数据,如果它有关联的子模型;不返回子模型的数据
【发布时间】:2019-09-14 02:44:53
【问题描述】:

在我使用 sequelize 和 postgresql 数据库的 node.js 应用程序中,我定义了三个模型:用户、购物篮和项目。用户模型有很多篮子,篮子有很多物品。

如果购物篮包含一个或多个项目,我正在尝试编写一个查询以仅返回用户和购物篮,而不返回项目。这个查询为我提供了我需要的数据(如果篮子有项目,则为用户和篮子),但它的问题是它也给了我所有的项目。

return await models.User.findAll({
    include: [{
      model: models.Basket,
      include: [{
        model: models.Item, 
        required: true
      }],
    }],
  });

【问题讨论】:

    标签: node.js postgresql sequelize.js


    【解决方案1】:

    如果您不需要 items 表中的任何内容,

    return await models.User.findAll({
      include: [{
        model: models.Basket,
        include: [{
          attributes: [],    // <----- Add this line
          model: models.Item, 
          required: true
        }],
      }],
    });
    

    【讨论】:

      猜你喜欢
      • 2021-06-08
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2018-05-15
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      相关资源
      最近更新 更多