Laravel 其中计数 > N
Laravel Where Count > N
我的应用程序中有 2 个模型:
1. Customer.php
2。 Car.php
现在我想 运行 查询 returns 所有拥有少于 2 辆车的客户。其中 2 是用户可以更改的数字。
我已经试过了,但是没有用,它只是 returns 所有客户记录:
$customers = Customer::whereHas("cars", function($query) {
$query->selectRaw("count(*) < ?", [2]);
})
->get();
编辑:
这两个模型链接在一个枢轴 table 中,这意味着一个客户可以拥有多于 1 辆车,而一辆车可以属于多于 1 个客户。
你试过这种方法吗?
$input = 2;
$customers = Customer::whereHas("cars", function($query) use ($input) {
$query->where(DB::raw("count(cars.id)"), "<", DB::raw($input))
})->get();
使用这个:
$customers = Customer::withCount('cars')
->having('cars_count', '<', 2)
->get();
所以,这是结果。
模型中的关系 Customer.php
public function cars()
{
return $this->belongsToMany('App\Car','car_customer','car_id','customer_id');
}
查询所有拥有 N 辆车的客户:
$userInput = 2;
$data = Customer::with('cars')
->withCount('cars')
->has('cars', '<', $userInput)
->orderBy('cars_count', 'desc')
->get();
其中 $userInput 是您的 'N'。
这是最好的方法:
$customers = Customer::has('cars','<', 2)->get();
我的应用程序中有 2 个模型:
1. Customer.php
2。 Car.php
现在我想 运行 查询 returns 所有拥有少于 2 辆车的客户。其中 2 是用户可以更改的数字。
我已经试过了,但是没有用,它只是 returns 所有客户记录:
$customers = Customer::whereHas("cars", function($query) {
$query->selectRaw("count(*) < ?", [2]);
})
->get();
编辑: 这两个模型链接在一个枢轴 table 中,这意味着一个客户可以拥有多于 1 辆车,而一辆车可以属于多于 1 个客户。
你试过这种方法吗?
$input = 2;
$customers = Customer::whereHas("cars", function($query) use ($input) {
$query->where(DB::raw("count(cars.id)"), "<", DB::raw($input))
})->get();
使用这个:
$customers = Customer::withCount('cars')
->having('cars_count', '<', 2)
->get();
所以,这是结果。
模型中的关系 Customer.php
public function cars()
{
return $this->belongsToMany('App\Car','car_customer','car_id','customer_id');
}
查询所有拥有 N 辆车的客户:
$userInput = 2;
$data = Customer::with('cars')
->withCount('cars')
->has('cars', '<', $userInput)
->orderBy('cars_count', 'desc')
->get();
其中 $userInput 是您的 'N'。
这是最好的方法:
$customers = Customer::has('cars','<', 2)->get();