我需要获得点赞最多的 5 个帖子

I need to get the 5 posts with the most likes

我现在正在做一个新闻系统,我需要得到点赞最多的前5个帖子。在我的代码和表格下方:

型号:

Post:

class Post extends Model
{
    use HasFactory;
    use HasTags;

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function likes()
    {
        return $this->hasMany(PostLike::class);
    }

    public function comments()
    {
        return $this->hasMany(PostComment::class);
    }
}

喜欢:

class PostLike extends Model
{
    protected $fillable = ['user_id', 'post_id', 'is_liked'];
    
    public function user(){
       return $this->belongsTo(User::class); 
    }
    public function post(){
        return $this->belongsTo(Post::class);
    }
    use HasFactory;
}

表格:

帖子: posts table

post_likes: post likes table

不知道为什么你有一个 is_liked 布尔值,因为如果关系存在,它就会喜欢。但这应该有效

Post::withCount('likes')->orderBy('likes_count', 'desc')->take(5)->get();