在我使用 sequelize 和 postgresql 数据库的 node.js 应用程序中,我定义了三个模型:用户、购物篮和项目。用户模型有很多篮子,而篮子里有很多物品。
如果篮子包含一个或多个项目,我正在尝试编写一个查询以仅返回用户和篮子,而不返回项目。这个查询让我得到我需要的数据(如果篮子里有物品,则为用户和篮子),但问题在于它也给了我所有的物品。
return await models.User.findAll({
include: [{
model: models.Basket,
include: [{
model: models.Item,
required: true
}],
}],
});
最佳答案
如果您不需要 items 表中的任何内容,
return await models.User.findAll({
include: [{
model: models.Basket,
include: [{
attributes: [], // <----- Add this line
model: models.Item,
required: true
}],
}],
});
关于node.js - Sequelize : query to include a parent model's data if it has associated children; don't return the child model's data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57921482/