【发布时间】:2020-11-10 08:20:56
【问题描述】:
我有一个产品、cmets 和子 cmets 表。
Products.php 模式
public function comments()
{
return $this->morphMany('App\Models\Comment', 'commentable')->orderBy('id');
}
Comment.php 模型
public function children()
{
return $this->hasMany('App\Models\ChildComment');
}
我现在的目标是执行一个雄辩的查询,它返回 products 表,但按comments_count + child_comments_count 排序。
目前,这就是我获得totalCommentsCount 属性的方式。我知道它并不完美,但我不知道如何更好地做到这一点......我也无法通过此属性对 eloquent 查询进行排序,因为此时查询已经执行:
public function getCommentsAndChildrenCountAttribute(){
$comments = $this->comments()->with('children')->withCount('children')->get();
$count = 0;
foreach($comments as $comment){
$count += $comment->children_count + 1;
}
return $count;
}
有人知道怎么做吗?
【问题讨论】:
标签: php mysql laravel eloquent sql-order-by