Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do table aliases using sequelize?

I need to do something like this. Where you can put a alias in front of the column name. o. c. etc

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

Here is the entire query im trying to replicate in 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

What I tried

attributes: ['c.id', ['comment_id'], 'c.comment', 'r.id', ['reply_id'], 'r.parent_comment_id', 'r.comment', ['reply_comment']]

Documentation from sequelize only shows how to do one attribute

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

SELECT foo AS baz ...

like image 964
jerrya92 Avatar asked Aug 19 '17 05:08

jerrya92


1 Answers

Each field you want an alias to, you need to pass as a two position array.

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.
    }
  ]
});
like image 125
Beto Raposa Avatar answered Nov 16 '22 18:11

Beto Raposa