按 hasMany 记录数排序 - COUNT(RelatedModel.field)
我有一个模型 Track,它有很多投票。投票模型有一个称为“值”的字段。我想做的是按照投票值的总和对 Track 记录进行排序(不幸的是,这意味着我无法使用 counterCache)。
当然,尝试输入类似 'order'=>'SUM(Vote.value)'
的内容会失败,并出现“未知列...”错误。
我只需将所有内容放入 find('all') 中,然后再进行排序,但我也需要分页。
我想到的最好的想法是在 Track 模型中添加一个字段来跟踪所有投票的总价值 - 类似于 counterCache 所做的,但反映了不同投票的不同价值。
有没有更简单的方法来做到这一点?
感谢您的阅读!
I have a model, Track, that hasMany Vote. the Vote model has a field called "value". What I wish to do is to sort Track records by the sum of the values of their votes (which means unfortunately I can't use counterCache).
Of course, trying to put something like 'order'=>'SUM(Vote.value)'
fails with an "unknown column..." error.
I would just get everything in a find('all') and then sort it out afterwards, but I need pagination too.
The best idea I've come up with is to add a field to the Track model that keeps track of the total value of all votes - something like what counterCache does but reflecting the different value of various votes.
Is there an easier way to do this?
Thanks for reading!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,我最终在 Track 模型中添加了一列(“vote_score”),并在添加/删除投票时更新它。这是代码,以防有人感兴趣。它似乎有效,但尚未进行广泛测试。在投票模型中:
Well, I ended up adding a column ("vote_score") to the Track model and updating it when a vote is added/deleted. Here's the code, in case anyone is interested. It appears to work, haven't tested it extensively though. In the Vote model: