dongmufen8105 2017-08-18 09:10
浏览 30
已采纳

获得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');
}
  • 写回答

2条回答 默认 最新

  • doupu3635 2017-08-18 14:27
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线