房间模型
<?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()
排序?
谢谢
答案 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();