删除联接查询结果中的前缀表名

时间:2018-12-28 12:55:37

标签: mysql node.js sequelize.js sequelize-typescript

使用nodejs(10.15.0),sequelize(4.42.0)和MySQL,尝试在联接查询中从结果中删除表路径。

Table1
    .findAll({
      attributes: ['id', 'name', 'other'],
      include: [{
        attributes: ['code_id'],
        model: Table2,
        nested: false,
        required: true,
      }],
      raw: true,
    })

查询结果

[
  {
    "id": 1,
    "name": "stuff",
    "other": true,
    "table2.code_id": 1,
  }
]

期待发生

      [
  {
    "id": 1,
    "name": "stuff",
    "other": true,
    "code_id": 1,
  }
]

1 个答案:

答案 0 :(得分:1)

删除raw: true,-阻止Sequelize将结果解析为对象。如果您不想使用模型实例,则需要为结果编写自己的解析器。

请注意,它将解析为以下结构(“ table2”将是一个属性):

[
  {
    "id": 1,
    "name": "stuff",
    "other": true,
    "table2": {
      "code_id": 1,
    }
  }
]

或者,您可以为子行加上别名,但是请注意,除非您创建一个映射到它的VIRTUAL字段,否则它只会进入dataValues

Table1
.findAll({
  attributes: [
    'id', 'name', 'other',
    [sequelize.col('table2.code_id'), 'code_id'], // aliased here
  ],
  include: [{
    attributes: [],
    model: Table2,
    required: true,
  }],
  raw: true,
})
相关问题