【问题标题】:Laravel: Call to undefined method Illuminate\Database\Eloquent\Collection::where()Laravel:调用未定义的方法 Illuminate\Database\Eloquent\Collection::where()
【发布时间】:2014-03-17 00:54:44
【问题描述】:

我的这个控制器功能有问题。该函数采用可选的“搜索”参数,并使用它在雇主的可用工作中搜索关键字。当我调用此函数时,出现以下错误。

调用未定义的方法 Illuminate\Database\Eloquent\Collection::where()

这是我的相关代码。任何建议将不胜感激!

路由:(前缀:'/api/v1/')

Route::get('employer/{employerId}/jobs', 'EmployersController@getJobs');

控制器:

public function getJobs ($employerId) {

    $search = Input::get('query');

    $jobs = Job::getAvailableByEmployer($employerId, $search);
    return $jobs;
}

型号:

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;
}

【问题讨论】:

  • 提示:>get(); PS:还要考虑ORAND 的优先级
  • 我必须在这里遗漏一些非常明显的东西。我环顾四周寻找涉及您的提示的解决方案,但似乎失败了。对不起布拉。
  • 为什么你认为$jobs 必须有whereorWhere 方法?
  • 是的,应该的。但是$jobs 对象没有where 方法。当您执行 if ($search) 代码时 - $jobs 已根据第一行中给出的查询进行过滤。
  • ohhhhhhhhhhhhhhh......为什么如果整个查询不是',你会调用一个执行数据库数据检索的->get()方法吗?还没准备好?

标签: php search laravel undefined where


【解决方案1】:

让你的函数像这样:

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;
}

现在这样称呼它(scope 让您可以静态调用):

$jobs = Job::getAvailableByEmployer($employerId, $search)->get();

还请记住,一旦您调用 get(),您将无法进行任何查询,因为它不再是 Query Builder,而是 Collection 对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2016-03-10
    • 2016-10-20
    • 2015-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多