序列化关联模型查询

时间:2018-07-02 21:24:10

标签: javascript express associations sequelize.js

我正在尝试在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非常陌生。

要补充一点,我确实希望所有这些相关模型都在返回的响应中,但目前甚至连雕像模型的响应都被吞噬了……

1 个答案:

答案 0 :(得分:0)

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

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

您还可以包括所有关联的模型,而无需单独指定它们

Statue.findAll({ include: [{ all: true }]});

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