mysql 如何将所有行数据置于一个数组下进行sequelize include操作

7d7tgy0s  于 2023-05-21  发布在  Mysql
关注(0)|答案(1)|浏览(74)

我有以下代码使用sequelize和mySQL数据库编写:

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"
      }
    },
jmp7cifd

jmp7cifd1#

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: [], // no nesting 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"
  }
]

相关问题