RIT*_*NAG 2 php eloquent laravel-4
我的控制器上的以下代码段有问题:
$opportunity_date = $oppr_arr->opportunity_date;
$locations_array_result = explode(",",$locations_array_result);
$usersCount = User::where('activated', '=', 1)
->where('group_id', '=', 1)
->where('availability_date', '<=', $opportunity_date)
->get();
foreach ($locations_array_result as $param) {
$usersCount = $usersCount->whereHas('desiredLocation', function ($q) use($param) {
$q->where('location_id', '=', $param );
});
}
$usersCount = $usersCount->count();
Run Code Online (Sandbox Code Playgroud)
当我运行它时,它给了我以下错误:
Call to undefined method Illuminate\Database\Eloquent\Collection::whereHas()
Run Code Online (Sandbox Code Playgroud)
我的人际关系是这样建立的:
用户模型
public function desiredLocation() {
return $this->belongsToMany('Location', 'user_desired_location');
}
Run Code Online (Sandbox Code Playgroud)
位置模型
class Location extends \Eloquent {
protected $table = 'locations';
protected $fillable = array('name');
public function country() {
return $this->belongsTo('Country');
}
}
Run Code Online (Sandbox Code Playgroud)
user_desired_location表的数据库结构是:
- id
- user_id
- location_id
Run Code Online (Sandbox Code Playgroud)
你打电话get太早了,这是在你想要之前运行查询。在foreach循环解决之后移动它:
$usersCount = User::where('activated', '=', 1)
->where('group_id', '=', 1)
->where('availability_date', '<=', $opportunity_date);
foreach ($locations_array_result as $param) {
$usersCount = $usersCount->whereHas('desiredLocation', function($q) use($param){
$q->where('location_id', '=', $param );
});
}
$users = $usersCount->get();
$usersCount = $users->count();
Run Code Online (Sandbox Code Playgroud)
另请注意:如果您感兴趣的只是计数并且您不会使用实际用户,则无需调用get然后count;这通过实际获取所有用户并在 PHP 端计算它会产生不必要的负载。相反,count直接使用,Eloquent 将发出一个COUNT()查询,在数据库端执行。像这样:
$usersCount = $usersCount->count();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9842 次 |
| 最近记录: |