Allow sorting on relations' columns
This commit is contained in:
parent
ec0a990a2b
commit
aa396620fa
20
lib/sql.js
20
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(',');
|
||||
|
|
|
@ -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: {
|
||||
|
|
Loading…
Reference in New Issue