【问题标题】:SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous Laravel whereHas returning errorSQLSTATE [23000]:完整性约束违规:1052 列 \'id\' 在 where 子句中不明确 Laravel whereHas 返回错误
【发布时间】:2022-08-18 13:28:51
【问题描述】:

您好,我想通过 laravel 9 中的标签和类别过滤我的回复。我的代码是:

$posts = Post::when($categoryId > 0, function($query) use ($categoryId) {
            return $query->where(\'category_id\', \'=\', $categoryId);
        })
        ->when($tagId > 0, function($query) use ($tagId){
            return $query->whereHas(\'tags\', function($query) use ($tagId) {
                return $query->where(\'id\', $tagId);
            });
        })
        ->get();

        return view(\'blog::posts.index\', compact(\'posts\', \'categories\'));

但我收到了这个错误: SQLSTATE [23000]:违反完整性约束:1052 列 \'id\' 在 where 子句中不明确

select * from `posts` where exists (select * from `tags` inner join `post_tag` on `tags`.`id` = `post_tag`.`tag_id` where `posts`.`id` = `post_tag`.`post_id` and `id` = 4)

    标签: eloquent many-to-many laravel-9 wherehas


    【解决方案1】:

    将代码更改为此

    $posts = Post::when($categoryId > 0, function($query) use ($categoryId) {
                return $query->where('category_id', '=', $categoryId);
            })
            ->when($tagId > 0, function($query) use ($tagId){
                return $query->whereHas('tags', function($query) use ($tagId) {
                    return $query->where('tag.id', $tagId);
                });
            })
            ->get();
    
            return view('blog::posts.index', compact('posts', 'categories'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2019-02-22
      • 2021-08-16
      • 2021-10-11
      • 1970-01-01
      • 2020-10-13
      • 2013-10-16
      相关资源
      最近更新 更多