获得laravel投票最多的回复

I have the reply relationship with like & unlike model. User can like for their best reply and unlike for bad reply. The like & unlike relationship is almost same,just store in different table. Now i want to get the replies that having most like & reply that having most unlike, compare them and show only the replies which have most number of vote. How can i achieve it?

In my Discussion Model

public function replies(){
    return $this->hasMany('App\Forum\Reply');
}

In Reply Model

public function discussion(){
    return $this->belongsTo('App\Forum\Discussion');
}

public function user(){
    return $this->belongsTo('App\User');
}

public function likes(){
    return $this->hasMany('App\Forum\Like');
}

In the like model

public function user(){
    return $this->belongsTo('App\User');
}

public function reply(){
    return $this->belongsTo('App\Forum\Reply');
}

I think you can use Eloquents withCount here.

So you'd have something like:

$mostLikedReply = Reply::withCount('likes')->orderBy('likes_count', 'desc')->first();
$mostUnlikedReply = Reply::withCount('unlikes')->orderBy('unlikes_count', 'desc')->first();

Note that withCount will place a {relation}_count column on your resulting models. That's why the orderBy is ordering on what the withCount applies, then by grabbing the first result, it should be the highest liked/unliked reply, from here you can compare what you need.

Read more about counting relations here

How about

$mostLikedReply = $discussion->replies->sortByDesc(function($reply) {  
    return $reply->likes->count();  
}->first();

This will give you the model for the most liked reply.

And the same for most unliked reply and then compare the two? I guess at that point you can maybe merge the whole stuff if you need to.