如何使用sequelize做表别名?

时间:2017-08-19 05:21:50

标签: mysql sequelize.js

我需要做这样的事情。您可以在列名称前面添加别名的位置。 O操作。 C。等

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

以下是我试图在sequelize中复制的整个查询

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']]

sequelize中的文档仅显示如何执行一个属性

Model.findAll({
  attributes: ['foo', ['baz']]
});

SELECT foo AS baz ...

4 个答案:

答案 0 :(得分:3)

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

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.
    }
  ]
});

答案 1 :(得分:0)

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

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

答案 2 :(得分:0)

您可以为任何表命名,如下所示:

comments.belongsTo(comments, , { as: 'r', foreignKey: 'id' })
comments.hasMany(comments, { foreignKey: 'parent_comment_id' )

请注意,您必须严格指定关系的字段名称,以使其正常工作。

您可以在命名策略

中找到here

答案 3 :(得分:0)

您要尝试的是在Sequelize中使用自连接,即根据您所查询的查询。链接-> sequelize self join   创建自我联接关系模型后,您需要再次包含相同的模型。和属性部分,您必须创建与该模型相关的别名。这是下面的示例...我假设注释是您的模型..因为您尚未提供模型的任何代码...

Model.comment.findAll({
  attributes: [

    ['id', 'comment_id'],   // uses alias 'comment_id' for column 'c.id'
    comment                 // c.comment no alias
  ],
  includes: [
    {
      model: comment,
      attributes: [
    ["id"," reply_id"],      // r.id as reply_id
    parent_comment_id ,        //r.parent_comment_id no alias
     ["comment","reply_comment "] //r.comment as reply_comment
                 ] 
    }
  ]
});