我在控制器上的以下代码段遇到问题:
$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();
当我运行它时,它给了我以下错误:
Call to undefined method Illuminate'Database'Eloquent'Collection::whereHas()
我的关系是这样设置的:
用户模型
public function desiredLocation() {
return $this->belongsToMany('Location', 'user_desired_location');
}
位置模型
class Location extends 'Eloquent {
protected $table = 'locations';
protected $fillable = array('name');
public function country() {
return $this->belongsTo('Country');
}
}
user_desired_location
表的数据库结构为:
- id
- user_id
- location_id
您调用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();
另请注意:如果您感兴趣的只是计数并且您不会使用实际用户,则无需调用get
然后count
;这通过实际获取所有用户并在PHP端计数来产生不必要的负载。相反,直接使用count
,Eloquent 将发出COUNT()
查询,在数据库端执行此操作。这样:
$usersCount = $usersCount->count();