如何使用sequelize做表别名?

jer*_*a92 4 mysql sequelize.js

我需要做这样的事情。您可以在列名前面放置别名的位置。oc等

SELECT o.OrderID, o.OrderDate, c.CustomerName FROM...

这是我试图按顺序复制的整个查询

SELECT c.id AS comment_id, c.comment, r.id AS reply_id, r.parent_comment_id, r.comment AS reply_comment FROM (comments c) LEFT JOIN comments r ON c.id = r.parent_comment_id

我尝试了什么

attributes: ['c.id', ['comment_id'], 'c.comment', 'r.id', ['reply_id'], 'r.parent_comment_id', 'r.comment', ['reply_comment']]
Run Code Online (Sandbox Code Playgroud)

sequelize中的文档仅显示了如何做一个属性

Model.findAll({
  attributes: ['foo', ['baz']]
});
Run Code Online (Sandbox Code Playgroud)

选择foo AS baz ...

Bet*_*osa 5

您想要别名的每个字段,都需要作为两个位置数组传递。

Model.findAll({
  attributes: [
    'foo', // do not use alias
    ['bar', 'baz'],       // uses alias 'baz' for column 'bar'
    [Sequelize.col('related.foo'), 'related_foo']  // alias on includes
  ],
  includes: [
    {
      model: related,
      attributes: [] // empty to not generate nested atributes.
    }
  ]
});
Run Code Online (Sandbox Code Playgroud)


小智 0

当您为表创建别名时,您可以访问表中相应的列

e:g SELECT o.cols1, o.cols2 FROM table o