Allow sorting on relations' columns

This commit is contained in:
Diogo Doreto 2015-11-13 11:13:29 -02:00
parent ec0a990a2b
commit aa396620fa
2 changed files with 40 additions and 3 deletions

View File

@ -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(',');

View File

@ -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: {