Postgresql Knex,objective.js,如何按关联数排序
我有一个通过Knex和Objective使用Postgres的Express API 我想设置一个模型方法或作用域,该方法或作用域按照关联子对象的数量返回父模型实例数组 我已经仔细看过了一份反对文件 我已经看到了以下适合的SQL查询,但正在尝试在Knex中解决此问题:Postgresql Knex,objective.js,如何按关联数排序,postgresql,express,knex.js,objection.js,Postgresql,Express,Knex.js,Objection.js,我有一个通过Knex和Objective使用Postgres的Express API 我想设置一个模型方法或作用域,该方法或作用域按照关联子对象的数量返回父模型实例数组 我已经仔细看过了一份反对文件 我已经看到了以下适合的SQL查询,但正在尝试在Knex中解决此问题: SELECT SUM(O.TotalPrice), C.FirstName, C.LastName FROM [Order] O JOIN Customer C ON O.CustomerId = C.Id GRO
SELECT SUM(O.TotalPrice), C.FirstName, C.LastName
FROM [Order] O JOIN Customer C
ON O.CustomerId = C.Id
GROUP BY C.FirstName, C.LastName
ORDER BY SUM(O.TotalPrice) DESC
如果有人感兴趣,我只包括原始SQL查询,如下所示:
router.get('/leaderboard', async (req, res) => {
let results = await knex.raw('SELECT users_id, username, COUNT(acts.id) FROM acts INNER JOIN users ON acts.users_id = users.id GROUP BY users_id, username ORDER BY COUNT(acts.id) DESC');
console.log(results);
res.json(results.rows);
});
这就是使用knex()的方法: 但如果您真的在使用Objective.js,那么您应该为
订单
和客户
表设置模型,并执行以下操作:
await Order.query()
.select(sum('TotalPrice'), 'c.FirstName', 'c.LastName')
.joinRelated('customer as c')
.groupBy('c.FirstName', 'c.LastName')
.orderBy(sum('TotalPrice'), 'desc')
await Order.query()
.select(sum('TotalPrice'), 'c.FirstName', 'c.LastName')
.joinRelated('customer as c')
.groupBy('c.FirstName', 'c.LastName')
.orderBy(sum('TotalPrice'), 'desc')