Sequelize 关联模型查询

Posted

技术标签:

【中文标题】Sequelize 关联模型查询【英文标题】:Sequelize associations model queryies 【发布时间】: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 非常陌生。

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

【问题讨论】:

【参考方案1】:

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

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

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

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

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

【讨论】:

以上是关于Sequelize 关联模型查询的主要内容,如果未能解决你的问题,请参考以下文章

为啥 Sequelize 认为我的模型没有关联?

Sequelize - 子选择关联以过滤父模型

按关联模型排序时,Sequelize 抛出错误“无法找到模型 x 的有效关联”

Sequelize:模型未关联到 Model2

仅从 sequelize junction 模型返回指定的关联模型

查询联结表而不在 Sequelize 中获取两个关联