【发布时间】:2016-02-21 06:28:35
【问题描述】:
我在 Laravel 5.1 上运行
目前我面临一个与SELECT 查询相关的问题。
我有一个Category 模型。它具有属性:id、parent_id、name。
我想执行一个按类别名称和父类别名称过滤的搜索功能。
我有这个问题
public function index($parent_id = 0)
{
$query = Category::select('category.*');
if (\Input::get('q')) {
$q = \Input::get('q');
$query->leftJoin('category as parent', 'parent.id', '=', 'category.parent_id')
->where(function($query) use($q) {
$query->orWhere('category.name', 'LIKE', '%' . $q . '%')
->orWhere('parent.name', 'LIKE', '%' . $q . '%')
;
});
}
$query->where('parent_id', $parent_id); // update Nov 19, 2015 16:31
...
}
从这个脚本,我得到了错误
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'parent_id' in where clause is ambiguous (SQL: select count(*) as aggregate from `category` left join `category` as `parent` on `parent`.`id` = `category`.`parent_id` where `category`.`deleted_at` is null and (`category`.`name` LIKE %q% or `parent`.`name` LIKE %q%))
知道如何将另一个别名放入当前表(不是父表)?
【问题讨论】:
-
你能生成原始数据,让我们调整一下,然后运行新的原始数据吗?
-
@Drew 我意识到有一个 where 条件我忘了把表名放在列的前面。现在工作正常
-
你同意我们可以因为错字而关闭它?
-
@Drew 当然,你可以关闭它
标签: php mysql laravel eloquent relationship