【问题标题】:Laravel unary relationship on join table连接表上的Laravel一元关系
【发布时间】:2016-02-21 06:28:35
【问题描述】:

我在 Laravel 5.1 上运行

目前我面临一个与SELECT 查询相关的问题。

我有一个Category 模型。它具有属性:idparent_idname

我想执行一个按类别名称父类别名称过滤的搜索功能。

我有这个问题

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


【解决方案1】:

我意识到有一个WHERE 条件我没有在表名中输入。

$query->where('category.parent_id', $parent_id);

我输入category.后,现在可以正常使用了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 2018-06-14
    • 2019-05-08
    • 2021-07-23
    • 2021-07-17
    • 2021-02-28
    相关资源
    最近更新 更多