use*_*908 1 laravel eloquent laravel-5.6
我的应用中有 2 个模型:
1. 客户.php
2.汽车.php
现在我想运行一个查询,返回所有少于 2 辆车的客户。其中 2 是用户可以更改的数字。
我试过这个,但没有用,它只是返回所有客户记录:
$customers = Customer::whereHas("cars", function($query) {
$query->selectRaw("count(*) < ?", [2]);
})
->get();
Run Code Online (Sandbox Code Playgroud)
编辑: 这两个模型在数据透视表中链接,这意味着一个客户可以拥有超过 1 辆汽车,而一辆汽车可以属于多个客户。
Jon*_*eir 14
用这个:
$customers = Customer::withCount('cars')
->having('cars_count', '<', 2)
->get();
Run Code Online (Sandbox Code Playgroud)
小智 5
所以,结果如下。
模型中的关系Customer.php
public function cars()
{
return $this->belongsToMany('App\Car','car_customer','car_id','customer_id');
}
Run Code Online (Sandbox Code Playgroud)
查询获得拥有 N 辆车的所有客户:
$userInput = 2;
$data = Customer::with('cars')
->withCount('cars')
->has('cars', '<', $userInput)
->orderBy('cars_count', 'desc')
->get();
Run Code Online (Sandbox Code Playgroud)
其中$userInput是您的“N”。
| 归档时间: |
|
| 查看次数: |
11298 次 |
| 最近记录: |