mysql - 删除连接查询结果中的前缀表名

标签 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,
  }
]

最佳答案

删除 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,
})

关于mysql - 删除连接查询结果中的前缀表名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53958945/

相关文章:

node.js - Firebase 异步函数语法错误

mysql - 在JavaFX环境中使用JPA

php - 结合两个 ajax 调用 - 在 url 中存储多个 post 变量

mysql - 如何在表格中的任意两个日期之间进行减法?

python - 如何正确排序其中包含数字的字符串

jquery - 有什么办法可以让 jquery 与 node.io 一起工作吗?

node.js - 我无法在我的 gulp 项目中安装 gulp-sass 模块

sequelize.js - 嵌套包含不提供结果

node.js - Sequelize 不在 postgresql 中创建任何表

reactjs - 即使它不是空的,也返回一个空的 json