订购Bookshelf.js按相关列值获取

问题描述 投票:3回答:3

我正在使用Bookshelf.js / Knex.js,使用相关的子模型(称为公司)获取模型(称之为用户)。 我可以通过儿童模型上的字段订购 - company.name吗?

此外,如果这是可能的,我可以多排序,说company.name下降然后lastName上升

这是我当前的代码,仅适用于根模型字段。 qb.orderBy('company.name', 'desc')不起作用。

users.query(function(qb) {
  qb.orderBy('lastName', 'asc');
})
.fetch({withRelated: ['company']})
.then(success, error);
node.js bookshelf.js knex.js
3个回答
2
投票

请尝试以下方法:

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

我从https://github.com/tgriesser/bookshelf/issues/361得到了这个想法


1
投票

你可以这样做,而不需要一个函数:

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

在这里找到:Sort Bookshelf.js results with .orderBy()


0
投票

我想通过这样做解决了这个问题:

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
        },
    );

我通过内部连接所需的表来修改查询,并在排序之后(使用orderByRaw,因为我需要添加一些我认为不可能使用orderBy的排序)我按照post的id分组以摆脱重复的行。唯一的问题是它没有定义哪个actor名称(几种可能的)用于排序。

© www.soinside.com 2019 - 2024. All rights reserved.