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

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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?