【问题标题】:Remove prefix tablename in join query result删除连接查询结果中的前缀表名
【发布时间】:2019-05-26 07:17:07
【问题描述】:

使用 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,
  }
]

【问题讨论】:

  • 尝试将as: "code_id" 作为属性添加到includes-array 中的对象。

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


【解决方案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,
})

【讨论】:

  • 这不能作为错误“字段列表中的未知列 'table2.code'”工作,因为 table2 不是 db 表名,而是模型名。
  • @NoorFathima 我的示例中的任何地方都没有“代码”,所以我认为您有错字。也许你有“code”而不是“code_id”?
  • 我完全按照你的要求做了,我得到了SequelizeDatabaseError: The multi-part identifier " ... " could not be bound
猜你喜欢
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多