Laravel:调用未定义的方法 Illuminate\Database\Eloquent\Collection::where()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22445249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Call to undefined method Illuminate\Database\Eloquent\Collection::where()
提问by Monty Monro
I am having a problem in this controller function. The function takes an optional 'search' parameter and uses it to search through en employers available jobs for keywords. When I am calling this function I am getting the following error.
我在这个控制器功能中遇到了问题。该函数采用一个可选的“搜索”参数,并使用它来搜索雇主可用的关键字工作。当我调用此函数时,出现以下错误。
Call to undefined method Illuminate\Database\Eloquent\Collection::where()
调用未定义的方法 Illuminate\Database\Eloquent\Collection::where()
Here is my relevant code. Any advice would be much appreciated!
这是我的相关代码。任何建议将不胜感激!
Routes: (prefix: '/api/v1/')
路由:(前缀:'/api/v1/')
Route::get('employer/{employerId}/jobs', 'EmployersController@getJobs');
Controller:
控制器:
public function getJobs ($employerId) {
$search = Input::get('query');
$jobs = Job::getAvailableByEmployer($employerId, $search);
return $jobs;
}
Model:
模型:
public static function getAvailableByEmployer($employerId, $search=NULL)
{
$jobs = Job::where('jobs.employer_id', '=', $employerId)
->where('jobs.status', '=', 'Available')
->orderBy('jobs.created_at', 'desc')
->get();
if ($search)
{
$jobs->where('title', 'LIKE', '%'. $search .'%')
->orWhere('description', 'LIKE', '%'. $search .'%');
}
return $jobs;
}
采纳答案by The Alpha
Make your function like this:
让你的功能是这样的:
public function scopeGetAvailableByEmployer($query, $employerId, $search=NULL)
{
$query->where('employer_id', '=', $employerId)
->where('status', '=', 'Available')
->orderBy('created_at', 'desc');
if ($search)
{
$jobs->where('title', 'LIKE', '%'. $search .'%')
->orWhere('description', 'LIKE', '%'. $search .'%');
}
return $query;
}
Now call it like (scope
lets you call statically):
现在称之为(scope
让你静态调用):
$jobs = Job::getAvailableByEmployer($employerId, $search)->get();
Also remember that, once you call get()
then you can't make any query because that is not a Query Builder
anymore but a Collection
object.
还要记住,一旦你打电话,get()
你就不能进行任何查询,因为那Query Builder
不再是一个Collection
对象而是一个对象。