簡體   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