【问题标题】:Laravel Eloquent: Sort table by sum count of two tablesLaravel Eloquent:按两个表的总和对表进行排序
【发布时间】: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


    【解决方案1】:

    也许这段代码可以完成这项工作?

    Product::withCount([
        'comments as count_comments', 
        'comments.children as comments_count_children'
    ])->orderByRaw('count_comments + comments_count_children desc')->get();
    

    【讨论】:

      猜你喜欢
      • 2023-01-26
      • 1970-01-01
      • 2014-06-25
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 2012-12-16
      相关资源
      最近更新 更多