I'm using Bookshelf.js/Knex.js, fetching a model (call it user) with a related child model (call it company).
Can I order by a field on the child model - company.name
?
Also, if that's possible, can I multi sort, say company.name
descending then lastName
ascending
Here's my current code, which only works on root model fields. qb.orderBy('company.name', 'desc')
doesn't work.
users.query(function(qb) {
qb.orderBy('lastName', 'asc');
})
.fetch({withRelated: ['company']})
.then(success, error);
Try the following:
I got the idea from https://github.com/tgriesser/bookshelf/issues/361
I think I solved it by doing this:
I modify the query by inner joining with the desired tables and after sorting (using orderByRaw since I will need to add some more sorting that I think is not possible with orderBy) I group by the post's id to get rid of the duplicate rows. The only problem is that it's not defined which actor name (of several possible) is used for the sorting.
You can do it like this without the need of a function:
Found here: Sort Bookshelf.js results with .orderBy()