Order Bookshelf.js fetch by related column value

只愿长相守 提交于 2019-11-30 16:06:47

Try the following:

users
.fetch({withRelated: [
     {
         'company': function(qb) {
             qb.orderBy("name");
         }
     }
]})
.then(success, error);

I got the idea from https://github.com/tgriesser/bookshelf/issues/361

mezod

You can do it like this without the need of a function:

users.query(function(qb) {
  qb.query('orderBy', 'lastName', 'asc');
})
.fetch({withRelated: ['company']})
.then(success, error);

Found here: Sort Bookshelf.js results with .orderBy()

I think I solved it by doing this:

let postHits =
    await posts
        .query(qb => qb
            .innerJoin('post_actor_rel', function () {
                this.on('post.id', '=', 'post_actor_rel.post_id');
            })
            .innerJoin('actor', function () {
                this.on('post_actor_rel.actor_id', '=', 'actor.id');
            })
            .orderByRaw('actor.name ASC')
            .groupBy('id')
        )
        .fetchPage({
            withRelated: ['roles', 'themes', 'activity_types', 'subjects', 'educational_stages', 'images', 'documents', 'actors'],
            limit,
            offset
        },
    );

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!