gpt4 book ai didi

javascript - Sequelize 关联模型查询

转载 作者:行者123 更新时间:2023-12-03 22:39:42 24 4
gpt4 key购买 nike

我想在我的 findAll 表上做一个简单的 Statue 操作。然而 findAll 操作也会查看所有关联的模型,这不是我的预期行为。

我的雕像关联模型设置如下,

statue.associate = function(models) {
const { comment, image, like } = models;

statue.hasMany(comment, {
foreignKey: 'model_id',
constraints: false,
scope: {
model_name: 'statue'
}
});

statue.hasMany(image, {
foreignKey: 'model_id',
constraints: false,
scope: {
model_name: 'statue'
}
});

statue.hasMany(like, {
foreignKey: 'model_id',
constraints: false,
scope: {
model_name: 'statue'
}
});
};

当我运行时:
const statues = await Statue.findAll();

我取回了我想要的雕像对象,并按预期看到了这个 postgres 命令行输出。
SELECT "id", "title", "artist_desc", "artist_name", "artist_url", "statue_desc", "location", "created_at", "updated_at" FROM "statues" AS "statue";  

但我也看到,
SELECT "id", "user_id", "text", "model_name", "model_id", "created_at", "updated_at" FROM "comments" AS "comment" WHERE "comment"."model_name" = 'statue' AND "comment"."model_id" = 1;
SELECT "id", "model_name", "model_id", "url", "height", "width", "created_at", "updated_at" FROM "images" AS "image" WHERE "image"."model_name" = 'statue' AND "image"."model_id" = 1;
SELECT "id", "user_id", "model_name", "model_id", "created_at", "updated_at" FROM "likes" AS "like" WHERE "like"."model_name" = 'statue' AND "like"."model_id" = 1;

哪些是相关模型,但是我收到的输出是
return res.json(statues);

{}

任何方向都会非常有帮助。我对 postgres 和 express 非常陌生。

要补充的是,我确实希望返回响应中的所有这些相关模型,但目前甚至雕像模型响应也被吞没了......

最佳答案

要包含相关模型,您可以使用 eager loading

const statues = await Statue.findAll({include: [image]});

您还可以包含所有关联的模型,而无需单独指定它们
Statue.findAll({ include: [{ all: true }]});

从输出的 Angular 来看,请记录 statues 的值,并检查 DB 中是否有值。

关于javascript - Sequelize 关联模型查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51143904/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com