按 hasMany 记录数排序 - COUNT(RelatedModel.field)

发布于 2024-11-29 02:15:07 字数 359 浏览 2 评论 0原文

我有一个模型 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆消瘦 2024-12-06 02:15:07

好吧,我最终在 Track 模型中添加了一列(“vote_score”),并在添加/删除投票时更新它。这是代码,以防有人感兴趣。它似乎有效,但尚未进行广泛测试。在投票模型中:

public function afterSave(){
    $this->Track->id = $this->data['Vote']['track_id'];
    $this->Track->saveField('vote_score','vote_score' + $this->data['Vote']['value']);
}

public function beforeDelete(){
    $vote = $this->Vote->read();
    $this->Track->id = $vote['Vote']['track_id'];
    $this->Track->saveField('vote_score','vote_score' - $vote['Vote']['value']);
    return true;
}

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:

public function afterSave(){
    $this->Track->id = $this->data['Vote']['track_id'];
    $this->Track->saveField('vote_score','vote_score' + $this->data['Vote']['value']);
}

public function beforeDelete(){
    $vote = $this->Vote->read();
    $this->Track->id = $vote['Vote']['track_id'];
    $this->Track->saveField('vote_score','vote_score' - $vote['Vote']['value']);
    return true;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文