gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:47:22 28 4
gpt4 key购买 nike

我的 Controller 上的以下代码有问题:

$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();

关于php - 在 laravel 中调用未定义的方法 Illuminate\Database\Eloquent\Collection::whereHas(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26996218/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com