具有内连接的 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
Laravel scope with inner join
提问by GluePear
I have 2 tables, projects
and jobs
. jobs
has 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 张桌子,projects
和jobs
. 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.php
model 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
jobs
where (projects
.name
LIKE %test%))
列未发现:在1054未知列'projects.name 'where子句'(SQL:SELECT * FROM
jobs
哪里(projects
。name
LIKE%测试%))
In my JobsController.php
I have:
在我的JobsController.php
我有:
$searchResults = Job::Search($searchTerm)->get();
回答by xmhafiz
The parameter $query
in where(function($query)
is not the $query
that you passed in public function scopeSearch($query, $keyword)
该参数$query
在where(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 $query
in use()
或者你需要包括$query
in use()
$query->where(function() use ($keyword, $query)