Laravel Where Count > N

十年热恋 提交于 2020-06-17 09:54:36

问题


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 have less than 2 cars. Where 2 is a number that can be changed by the user.

I have tried this but it didn't work, it just returns all customer records:

$customers = Customer::whereHas("cars", function($query) {
    $query->selectRaw("count(*) < ?", [2]);
})
->get();

Edit: The two models are linked in a pivot table, meaning A customer can have more than 1 car and a Car can belong to more than 1 customer.


回答1:


Use this:

$customers = Customer::withCount('cars')
    ->having('cars_count', '<', 2)
    ->get();



回答2:


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'




回答3:


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



来源:https://stackoverflow.com/questions/50081540/laravel-where-count-n

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!