Pri*_*ika 1 php has-many laravel eloquent
我有一个模范客户,它有很多项目。我想在不包括其对象的情况下查找项目数。
客户模型包括:
public function numberOfProjects()
{
return $this->hasMany(Project::class)->count();
}
Run Code Online (Sandbox Code Playgroud)
在我的控制器中查询:
$customers = Customer::where(['is_active'=>1])
->with(['customerContactInformation'=> function ($query) {
$query->where('is_active',1);
}, 'numberOfProjects'])
->skip($skip)->take(10)
->get();
Run Code Online (Sandbox Code Playgroud)
它给了我错误:在整数上调用成员函数 addEagerConstraints()
尝试这个
客户模型
public function numberOfProjects()
{
return $this->hasMany(Project::class);
}
Run Code Online (Sandbox Code Playgroud)
控制器
$customers = Customer::where(['is_active'=>1])
->with(['customerContactInformation'=> function ($query) {
$query->where('is_active',1);
}])
->withCount('numberOfProjects') //you can get count using this
->skip($skip)
->take(10)
->get();
Run Code Online (Sandbox Code Playgroud)
那应该是工作
$customers = Customer::withCount('numberOfProjects')->get();
Run Code Online (Sandbox Code Playgroud)
WithCount 在特定状态
$customers = Customer::withCount([
'numberOfProjects',
'numberOfProjects as approved_count' => function ($query) {
$query->where('approved', true);
}
])
->get();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1172 次 |
| 最近记录: |