【问题标题】:I need to get the 5 posts with the most likes我需要得到点赞最多的5个帖子
【发布时间】:2021-10-20 05:21:36
【问题描述】:

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

型号:

帖子:

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

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    不知道为什么你有一个is_liked bool,因为如果关系存在,它就会被喜欢。但这应该工作

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

    【讨论】:

    • 因为“喜欢”可以是正面的,也可以是负面的(喜欢,我不喜欢)
    • 那么上面的代码只会根据大多数关系返回,积极的和消极的。
    猜你喜欢
    • 2021-11-02
    • 2021-10-20
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多