具有内连接的 Laravel 范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38362408/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 14:09:09  来源:igfitidea点击:

Laravel scope with inner join

phpmysqllaravelsearchinner-join

提问by GluePear

I have 2 tables, projectsand jobs. jobshas a column called project_id. In Laravel 5.2 I want to run a search that will return all jobs which belong to a project of a given search term. This SQL works:

我有 2 张桌子,projectsjobs. jobs有一个名为project_id. 在 Laravel 5.2 中,我想运行一个搜索,该搜索将返回属于给定搜索词的项目的所有工作。此 SQL 有效:

SELECT jobs.*, projects.name FROM jobs INNER JOIN projects ON jobs.project_id = projects.id WHERE projects.name LIKE "%$keyword%"

In my Job.phpmodel I have created a scope method, which errors:

在我的Job.php模型中,我创建了一个 scope 方法,该方法出错:

public function scopeSearch($query, $keyword)
{
    if ($keyword != '') {
        $query->where(function($query) use ($keyword) {
            $query->where('projects.name', 'LIKE', '%' . $keyword . '%')->join('projects', 'jobs.project_id', '=', 'projects.id');
        });
    }
    return $query;
}

This produces the error:

这会产生错误:

Column not found: 1054 Unknown column 'projects.name' in 'where clause' (SQL: select * from jobswhere (projects.nameLIKE %test%))

列未发现:在1054未知列'projects.name 'where子句'(SQL:SELECT * FROMjobs哪里(projectsnameLIKE%测试%))

In my JobsController.phpI have:

在我的JobsController.php我有:

$searchResults = Job::Search($searchTerm)->get();

回答by xmhafiz

The parameter $queryin where(function($query)is not the $querythat you passed in public function scopeSearch($query, $keyword)

该参数$querywhere(function($query)不是$query你传入public function scopeSearch($query, $keyword)

You can either remove it with just the query like below (as @Rob mentioned)

您可以仅使用如下查询将其删除(如@Rob 所述)

public function scopeSearch($query, $keyword)
{
    if ($keyword != '') {
        $query->where('projects.name', 'LIKE', '%' . $keyword . '%')->join('projects', 'jobs.project_id', '=', 'projects.id');
    }
    return $query;
}

or you need to include the $queryin use()

或者你需要包括$queryin use()

$query->where(function() use ($keyword, $query)