繁体   English   中英

Laravel雄辩的关系函数“ with”和“ groupBy”如何一起使用

[英]Laravel Eloquent relationship function “with” and “groupBy” how use it together

嗨,我与多对多建立了联系。 我需要普及,所以我想使用groupBy并进行查询。 但是我不知道如何引用关系表rent_car。

控制器:

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

模型用户;

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

模型车:

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

所以我的问题是我如何使用groupBy并使用“ with”函数进行计数。 我试图找到它,并且做出了一些像在控制器中显示的想法。

使用withCount()方法。
因此,您的代码可以像这样:

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

现在考虑选择列表中的rentcar_count字段。 希望这可以帮助。

编辑:
您要坚持使用group by 因此,将上面的代码更新为如下所示:

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

经过讨论
该代码有望正常运行:

Cars::with('caruser')
  ->withCount('caruser')
  ->where('caruser_count', '>', 0)
  ->orderBy('caruser_count', 'DESC')
  ->take(5)
  ->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM