douyan1972 2017-05-20 17:45
浏览 989
已采纳

Laravel Eloquent关系函数“with”和“groupBy”如何一起使用它

Hi i made relationship many-to-many and its working. I need make popularity so i want use groupBy and count with query. But i dont know how i can refer to relation table rent_car.

Controller:

 public function popularityCar()
{

 $total_raw = DB::raw('count(*) as total');
 $cars = User::with('rentcar')
        ->where('rentcar')
        ->select('car_id', $total_raw)
        ->groupBy('car_id')           
        ->get();
 dump($cars);   
 echo $cars;
          return view('user.popularityCar',['cars' => $cars]);
}

Model User;

    public function rentcar()
{
    return $this->belongsToMany(Cars::class,'rent_car','user_id','car_id')->withTimestamps()->withPivot('start', 'end');
}

Model Cars:

 public function caruser()
{
    return $this->belongsToMany(User::class,'rent_car','car_id','user_id');
}

So my question is how i can use groupBy and count with function "with". I trying found it and i made somethink like i showing in my controller.

  • 写回答

1条回答 默认 最新

  • dongliu4320 2017-05-20 18:19
    关注

    Use withCount() method.
    So your code can be like this:

     $cars = User::with('rentcar')
        ->withCount('rentcar')
        ->where('rentcar_count', '>', 0)
        ->get();
    

    Consider rentcar_count field in your select list now. Hope this helps.

    Edited:
    You're insisting to use group by. So update the code above to something like this:

     $cars = User::with('rentcar')
        ->select('car_id', \DB::raw('Count(car_id) as rentcar_count'))
        ->groupBy('car_id')           
        ->having('rentcar_count', '>', 0)
        ->get();
    

    After discussion:
    This code works fine hopefully:

    Cars::with('caruser')
      ->withCount('caruser')
      ->where('caruser_count', '>', 0)
      ->orderBy('caruser_count', 'DESC')
      ->take(5)
      ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!