Home > Blockchain >  I need to get the 5 posts with the most likes
I need to get the 5 posts with the most likes

Time:10-21

I'm currently making a news system, and I need to get the top 5 posts with the most likes. Below my code and tables:

Models:

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

Likes:

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

Tables:

posts: posts table

post_likes: post likes table

CodePudding user response:

No idea why you have a is_liked bool since if the relation exists, its liked. but this should work

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

  • Related