我正在使用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);
请尝试以下方法:
users
.fetch({withRelated: [
{
'company': function(qb) {
qb.orderBy("name");
}
}
]})
.then(success, error);
你可以这样做,而不需要一个函数:
users.query(function(qb) {
qb.query('orderBy', 'lastName', 'asc');
})
.fetch({withRelated: ['company']})
.then(success, error);
我想通过这样做解决了这个问题:
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名称(几种可能的)用于排序。