Sequelize hasMany 关联仅返回单个对象 [英] Sequelize hasMany association returns only a single object

查看:91
本文介绍了Sequelize hasMany 关联仅返回单个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hasMany 关联应该返回一个对象、权限列表?我有一个 user 记录和一些连接到它的 connections 记录.

The hasMany association should return a list of object, rights? I have a user record and a few connections records connected to it.

模型 connections:

userId: {
      field: 'user_id',
      type: DataTypes.STRING,
      allowNull: false
    }

模型 users:

(users as any).associate = function associate(models: any) {
    models.users.hasMany(models.connections, {
      as: 'connections',
      foreignKey: 'user_id'
    });
  };

我通过将 connections 模型添加到 sequelize 查询参数中来包含它:

I include the connections model by adding it to the sequelize query params:

include: [{ model: context.app.service('connections').Model, as: 'connections' }],

最终结果是 user 响应中的 connections 属性是单个对象,而不是对象数组.我记录了 Sequelize 的查询执行,并直接在数据库中尝试了 Sequelize 为这个特定调用所做的原始查询,它返回了一个记录列表,正如它应该的那样.但是当我通过 API 查询它时,它只返回一个对象而不是一个数组.

The end result is that the connections property in the user response is a single object instead of an array of objects. I logged the Sequelize’s query executions and tried directly in the DB the raw query that Sequelize does for this particular call and it returns a list of records, as it should. But when I query it through the API, it returns just a single object instead of an array.

推荐答案

原来来自 Sequelize 的查询需要标记为 raw.因此,在 sequelize 对象中,您必须包含 raw: true 参数.不幸的是,这将导致返回一个 Sequelize 本机对象(具有 defaultValues 属性的对象).您可以通过对 Sequelize 的结果调用 .get() 将其序列化为普通的 JavaScript 对象.

Turns out the query from Sequelize needs to be marked as raw. So, in the sequelize object, you gotta include the raw: true param. This will, unfortunately, result in returning a Sequelize native object (the one that has the defaultValues prop). You can get it serialized into a normal JavaScript object by calling .get() on the result from Sequelize.

所以,总而言之,您必须在与 include 属性相同的级别上添加 raw: true,如下所示:

So, to sum up, you gotta add raw: true on the same level as the include prop, like so:

{
  include: [{ model: ...],
  raw: true 
}

这篇关于Sequelize hasMany 关联仅返回单个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆