我有三个模型:user
、noun
和 usernoun
(PHP/Eloquent 中的user_noun
)。 user
和 noun
之间存在多对多的关系。 “pivot”表有一个额外的属性score
。我可以将此查询与 Eloquent 一起使用,将用户必须获得的每个名词的分数相加得到用户的总分:
$users = User::leftJoin('noun_user', 'user.id', 'noun_user.user_id')
->groupBy('user.id')
->select('user.*', DB::raw('sum(noun_user.score) as score'))
->orderBy('score', 'desc')
->get();
但我不知道如何让它在 Waterline 中工作。这有效,但当我取消注释 .populate('user')
行时无效。我需要填充 user
。
UserNoun
.find({})
//.populate('user')
.groupBy('user')
.sum('score')
.sort({ score: 'desc' })
.exec((err, usernouns) => {
return res.json(usernouns)
})
这是一个有效的 .native()
查询:
UserNoun.native(function(err, collection) {
collection.aggregate([
{
$lookup: {
from: 'user',
localField: 'user',
foreignField: '_id',
as: 'user'
}
},
{
$group: { _id: '$user', total: { $sum: '$score' } }
},
{
$sort : { total: -1 }
}
]).toArray(function (err, results) {
return res.json(results)
})
})
这个原生查询可以用 groupBy
和 populate
和 sum
在 Waterline 中重写吗?
最佳答案
从 Waterline@0.11.8 开始,唯一的方法是使用 native 查询。
顺便说一句,你可以在 User 模型中导出你的方法:
// User.js
module.exports = {
// ...
findTotalScores: function (callback) {
UserNoun.native(function(err, collection) {
if (err) {
return callback(err);
}
collection.aggregate([
{
$lookup: {
from: 'user',
localField: 'user',
foreignField: '_id',
as: 'user'
}
},
{
$group: { _id: '$user', total: { $sum: '$score' } }
},
{
$sort : { total: -1 }
}
]).toArray(callback);
});
}
};
你可以通过调用在你的 Controller 中使用它:
User.findTotalScores(function (err, results) {
return res.json(results);
});
https://stackoverflow.com/questions/41962540/
相关文章:
javascript - 如何处理 MongoDB 键名中的点?
mongodb - 为什么 Spring Data MongoDB 无法实例化这种嵌套类型结构?
node.js - mongodb错误: The 'cursor' option is requir
mysql - 在备份期间保持两个独立数据存储之间的完整性(MySQL 和 MongoDB)
node.js - 在 docker 容器中安装 Mongoose
ruby-on-rails - 通过 AWS opsworks 设置 mongodb