按嵌套关系计数对模型进行排序

Sort Model by a nested Relationship count

房间模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Room extends Model
{
    /**
     * Get the comments for the room.
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

评论模型

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{

    /**
     * Get the room that owns the comment.
     */
    public function room()
    {
        return $this->belongsTo('App\Room');
    }

    public function upvotes() {
        return $this->hasMany('App\Upvote');
    }
}

为模特点赞

namespace App;

use Illuminate\Database\Eloquent\Model;

class Upvote extends Model
{

    /**
     * Get the comment that the upvote belongs to.
     */    
    public function comment() {
        return $this->belongsTo('App\Comment');
    }
}

我如何才能获得按每个评论的赞成票数排序的房间评论列表?

我在网上搜索过,但只找到了有关按其定向关系对模型进行排序的答案,例如 $room->comments() 而不是按 $room->comments()->upvotes()?

排序

谢谢

您可以尝试使用连接和原始查询:

$comments = \App\Comment::join('upvotes', function($j) {
            $j->on('upvotes.comment_id', '=', 'comments.id');
        })
        ->where('comments.room_id', $roomId)
        ->with('upvotes')
        ->groupBy('comments.id')
        ->orderBy('count', 'desc')
        ->select((['comments.*', \DB::raw('COUNT(upvotes.comment_id) as count')]))->get();

使用 withCount() 方法计算每条评论的点赞数并创建 upvotes_count 属性:

 Comment::where('room_id', $roomId)
        ->withCount('upvotes')
        ->orderBy('upvotes_count', 'desc')
        ->get();