【问题标题】:Sequelize associations model queryiesSequelize 关联模型查询
【发布时间】:2018-07-02 21:24:10
【问题描述】:

我正在尝试对我的Statue 表执行简单的findAll 操作。但是,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 非常陌生。

补充一点,我确实希望所有这些关联模型都包含在返回响应中,但目前甚至连雕像模型响应都被吞没了......

【问题讨论】:

    标签: javascript express associations sequelize.js


    【解决方案1】:

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

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

    您还可以包含所有关联的模型而不单独指定它们

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 2022-10-23
      • 2016-12-19
      • 2016-09-30
      • 1970-01-01
      相关资源
      最近更新 更多