Laravel Where Count > N

前端 未结 3 1407
攒了一身酷
攒了一身酷 2021-01-24 07:22

I have 2 models in my app:

1. Customer.php

2. Car.php

Now I would like to run a query that returns all customers that h

相关标签:
3条回答
  • 2021-01-24 07:48

    Use this:

    $customers = Customer::withCount('cars')
        ->having('cars_count', '<', 2)
        ->get();
    
    0 讨论(0)
  • 2021-01-24 07:51

    So , here is the result.

    Relation in model Customer.php

    public function cars() { return $this->belongsToMany('App\Car','car_customer','car_id','customer_id'); }

    Query to get all customers with N cars.

     $userInput = 2;
     $data = Customer::with('cars')
                    ->withCount('cars')
                    ->has('cars', '<', $userInput)
                    ->orderBy('cars_count', 'desc')
                    ->get();
    

    $userInput is your 'N'

    0 讨论(0)
  • 2021-01-24 07:51

    Have you tried this ?

    $input = 2; $customers = Customer::whereHas("cars", function($query) use ($input) { $query->where(DB::raw("count(cars.id)"),"<",DB::raw($input)) })->get();

    0 讨论(0)
提交回复
热议问题