diff --git a/lib/sql.js b/lib/sql.js index 23f576b..d3492f9 100644 --- a/lib/sql.js +++ b/lib/sql.js @@ -863,10 +863,24 @@ SQLConnector.prototype.buildOrderBy = function(model, order) { var clauses = []; for (var i = 0, n = order.length; i < n; i++) { var t = order[i].split(/[\s,]+/); - if (t.length === 1) { - clauses.push(self.columnEscaped(model, order[i])); + var colName; + if (t[0].indexOf('.') < 0) { + colName = self.columnEscaped(model, t[0]); } else { - clauses.push(self.columnEscaped(model, t[0]) + ' ' + t[1]); + // Column name is in the format: relationName.columnName + var colSplit = t[0].split('.'); + // Find the name of the relation's model ... + var modelDef = this.getModelDefinition(model); + var relation = modelDef.model.relations[colSplit[0]]; + var colModel = relation.modelTo.definition.name; + // ... and escape them + colName = self.columnEscaped(colModel, colSplit[1]); + } + + if (t.length === 1) { + clauses.push(colName); + } else { + clauses.push(colName + ' ' + t[1]); } } return 'ORDER BY ' + clauses.join(','); diff --git a/test/sql.test.js b/test/sql.test.js index b0186cc..e6859d4 100644 --- a/test/sql.test.js +++ b/test/sql.test.js @@ -364,6 +364,29 @@ describe('sql connector', function() { }); }); + it('builds SELECT with INNER JOIN and order by relation columns', function () { + var sql = connector.buildSelect('order', { + where: { + customer: { + fields: { + 'name': true, + 'vip': true + } + } + }, + order: ['customer.vip DESC', 'customer.name ASC'] + }); + + expect(sql.toJSON()).to.eql({ + sql: 'SELECT DISTINCT `ORDER`.`ID`,`ORDER`.`DATE`,`ORDER`.`CUSTOMER_NAME`,' + + '`ORDER`.`STORE_ID` FROM `ORDER` INNER JOIN ( SELECT `CUSTOMER`.`NAME`,' + + '`CUSTOMER`.`VIP` FROM `CUSTOMER` ORDER BY `CUSTOMER`.`NAME` ) AS `CUSTOMER`' + + ' ON `ORDER`.`CUSTOMER_NAME`=`CUSTOMER`.`NAME` ORDER BY ' + + '`CUSTOMER`.`VIP` DESC,`CUSTOMER`.`NAME` ASC', + params: [] + }); + }); + it('builds SELECT with multiple INNER JOIN', function () { var sql = connector.buildSelect('customer', { where: {