sequelize/sequelize — pull request #1299 by overlookmotel (2014-01-27 03:00:25+00:00)
Title: Order by nested associations

PR for https://github.com/sequelize/sequelize/issues/1250

Allows ordering by attributes of nested associations.

Syntax:

Company.findAll({ include: [ Division ], order: [ [ Division, 'name' ] ] })
Company.findAll({ include: [ Division ], order: [ [ Division, 'name', 'DESC' ] ] })
Company.findAll({
include: [ { model: Division, as: 'Div' } ],
order: [ [ { model: Division, as: 'Div' }, 'name' ] ]
})
Company.findAll({
include: [ { model: Division, include: [ Department ] } ],
order: [ [ Department, 'name' ] ]
})

I also had to amend sequelize.col() and sequelize.fn() so you can do things like:

Company.findAll({
include: [ Division ],
order: [ [ sequelize.fn('IFNULL', sequelize.col(Division, 'name'), 'no name'), 'DESC' ] ]
})

Does not break backwards compatibility. All tests complete OK for MySQL.