如何将Sequelize include操作下的所有行数据放入一个数组中

huangapple go评论75阅读模式
英文:

How to bring all row data under one array for sequelize include operations

问题

以下是您要翻译的内容:

我使用sequelize和MySQL数据库编写了以下代码:

```javascript
return await SelectedEmployees.findAndCountAll({
    attributes: ['organization_id'],
    include: [
      {
        model: User,
        as: 'user',
        attributes: ['id', [sequelize.literal(`CONCAT(user.first_name, ' ', user.last_name)`), 'name'], 'email'],
        where: {
          'email': {
            [Op.like]: `%${search}%`
          }
        }
      }
    ],
    where: {
      courseId: course_id,
    },
  });

使用上述代码,我得到了以下响应:

{
  "count": 3,
  "rows": [
    {
      "organization_id": 101023,
      "user": [
        {
          "id": 1,
          "name": "User One",
          "email": "userOne@email.com"
        }
      ]
    },
    {
      "organization_id": 101023,
      "user": [
        {
          "id": 2,
          "name": "User Two",
          "email": "userTwo@email.com"
        }
      ]
    },
    {
      "organization_id": 957256,
      "user": [
        {
          "id": 3,
          "name": "User Three",
          "email": "userThree@email.com"
        }
      ]
    }
  ]
}

然而,很明显,每个user对象都返回为对象数组,而不仅仅返回一个对象。我的目标是简化对象并获得以下输出:

{
  "count": 3,
  "rows": [
    {
      "organization_id": 101023,
      "id": 1,
      "name": "User One",
      "email": "userOne@email.com"
    },
    {
      "organization_id": 101023,
      "id": 2,
      "name": "User Two",
      "email": "userTwo@email.com"
    },
    {
      "organization_id": 957256,
      "id": 3,
      "name": "User Three",
      "email": "userThree@email.com"
    }
  ]
}

我尝试使用raw: truenest: true,但得到了略有不同的结果,其中idnameemail字段位于user对象下,如下所示:

{
  "organization_id": 101023,
  "user": {
    "id": 1,
    "name": "User One",
    "email": "userOne@email.com"
  }
}
英文:

I have the following code written using sequelize and with mySQL database:

return await SelectedEmployees.findAndCountAll({
    attributes: ['organization_id'],
    include: [
      {
        model: User,
        as: 'user',
        attributes: ['id', [sequelize.literal(`CONCAT(user.first_name, ' ', user.last_name)`), 'name'], 'email'],
        where: {
          'email': {
            [Op.like]: `%${search}%`
          }
        }

      }
    ],
    where: {
      courseId: course_id,
    },
  });

With the above code I am getting the following response:



{
  "count": 3,
  "rows": [
    {
      "organization_id": 101023,
      "user": [
        {
          "id": 1,
          "name": "User One",
          "email": "userOne@email.com"
        }
      ]
    },
    {
      "organization_id": 101023,
      "user": [
        {
          "id": 2,
          "name": "User Two",
          "email": "userTwo@email.com"
        }
      ]
    },
    {
      "organization_id": 957256,
      "user": [
        {
          "id": 3,
          "name": "User Three",
          "email": "userThree@email.com"
        }
      ]
    }
  ]
}


However, it's visible that for each user object it's being returned as an array of objects rather than just returning an object. My goal is to simplify the object and have the following output:


{
  "count": 3,
  "rows": [
    {
      "organization_id": 101023,
      "id": 1,
      "name": "User One",
      "email": "userOne@email.com"
    },
    {
      "organization_id": 101023,
      "id": 2,
      "name": "User Two",
      "email": "userTwo@email.com"
    },
    {
      "organization_id": 957256,
      "id": 3,
      "name": "User Three",
      "email": "userThree@email.com"
    }
  ]
}

I tried using raw: true and nest: true but got slightly different result where the id, name, and email fields are going under the user object as shown below:

    {
      "organization_id": 101023,
      "user": {
        "id": 1,
        "name": "User One",
        "email": "userOne@email.com"
      }
    },

答案1

得分: 1

nest: true 表示你想要嵌套它(放入一个对象中)。这就是为什么你在 user 对象下得到 nameemail

看着你的期望结果,你不想要嵌套,所以是 raw: true; nest: false,然而,这会导致以下结果:

{
  "organization_id": 101023,
  "user.id": 1,
  "user.name": "User One",
  "user.email": "userOne@email.com"
}

Sequelize 会在属性名称前添加关联/表名称作为前缀(我认为这是为了避免在多个包含项时出现命名冲突)。

如果你想要控制这些属性在扁平化对象中的命名,你需要在顶级添加 attributes 选项。

await SelectedEmployees.findAndCountAll({
  attributes: [
    'organization_id',
    [sequelize.col('user.id'), 'id'],
    [sequelize.literal(`CONCAT(user.first_name, ' ', user.last_name)`), 'name'],
    [sequelize.col('user.email'), 'email']
  ],
  include: [
    {
      model: User,
      as: 'user',
      attributes: [], // 不嵌套属性
      where: {
        email: {
          [Op.like]: `%${search}%`
        }
      }
    }
  ],
  where: {
    courseId: course_id,
  },
});

这将导致以下结果:

[
  {
    "organization_id": 101023,
    "id": 1,
    "name": "User One",
    "email": "userOne@email.com"
  },
  {
    "organization_id": 101023,
    "id": 2,
    "name": "User Two",
    "email": "userTwo@email.com"
  }
]
英文:

nest: true means you want to nest it(put into an object). That's why you get name and email under user object.

Looking at your expected result, you do not want to nest, so that is raw: true; nest: false, however, this results in

{
  "organization_id": 101023,
  "user.id": 1,
  "user.name": "User One",
  "user.email": "userOne@email.com"
}

Sequelize will add association/table name as a prefix to attributes name (which I think is to avoid naming conflicts when there are multiple includes).

If you want to control the naming of these attributes in the flattened object, you need to add attributes option in the top-level.

await SelectedEmployees.findAndCountAll({
  attributes: [
    'organization_id',
    [sequelize.col('user.id'), 'id'],
    [sequelize.literal(`CONCAT(user.first_name, ' ', user.last_name)`), 'name'],
    [sequelize.col('user.email'), 'email']
  ],
  include: [
    {
      model: User,
      as: 'user',
      attributes: [], // no nesting attributes
      where: {
        email: {
          [Op.like]: `%${search}%`
        }
      }
    }
  ],
  where: {
    courseId: course_id,
  },
});

this will result in

[
  {
    "organization_id": 101023,
    "id": 1,
    "name": "User One",
    "email": "userOne@email.com"
  },
  {
    "organization_id": 101023,
    "id": 2,
    "name": "User Two",
    "email": "userTwo@email.com"
  }
]

huangapple
  • 本文由 发表于 2023年5月17日 22:07:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76273014.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定