简体   繁体   中英

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

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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