在laravel中调用未定义的方法Illuminate \ Database \ Eloquent \ Collection :: whereHas()

时间:2014-11-18 14:04:30

标签: php laravel-4 eloquent

我在控制器上遇到以下代码问题:

$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

1 个答案:

答案 0 :(得分:3)

您过早地调用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();