You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Laravel Eloquent按分类名称筛选文章?

Laravel Eloquent按分类名称筛选文章报错解决方法

你遇到的错误是因为with('category')仅做关联模型的预加载,不会将categories表加入主查询的关联中,直接在where里引用category.name时,数据库只能看到articles表的字段,自然会提示列不存在。

正确解决方案(推荐用whereHas)

使用whereHas方法针对关联模型添加筛选条件,它会生成子查询来匹配分类名称:

$article = Article::with('category')
    ->when(request()->q, function($query) {
        $query->whereHas('category', function($subQuery) {
            $subQuery->where('name', 'like', '%' . request()->q . '%');
        });
    })
    ->latest()
    ->paginate(10);

备选方案(使用join关联查询)

如果你习惯用原生关联查询的方式,也可以手动joincategories表,注意要指定查询的字段避免冲突:

$article = Article::with('category')
    ->when(request()->q, function($query) {
        $query->join('categories', 'articles.category_id', '=', 'categories.id')
              ->where('categories.name', 'like', '%' . request()->q . '%')
              ->select('articles.*'); // 只查询articles表的字段,避免与categories表字段重名
    })
    ->latest()
    ->paginate(10);

两种方法的区别:

  • whereHas采用子查询逻辑,更符合Eloquent的关联设计,无需担心字段冲突,适合仅需筛选关联条件的场景
  • join是直接关联表查询,性能上在大数据量时可能有差异,需要手动处理字段选择

内容的提问来源于stack exchange,提问作者ASHafizullah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 14:11:29