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

时间:2017-03-28 20:45:46

标签: laravel laravel-5 laravel-5.4

房间模型

<?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');
    }
}

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');
    }
}

我如何能够获得房间的评论列表,这些评论按每个评论的upvotes计数排序?

我在网上搜索过,并且只设法找到有关让模型按其定向关系排序的答案,例如$room->comments()而不是按$room->comments()->upvotes()排序?

谢谢

2 个答案:

答案 0 :(得分:0)

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

$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();

答案 1 :(得分:0)

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

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