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

Laravel9前端展示指定分类文章问题:JSON存储分类无法遍历

在Laravel 9中筛选JSON字段存储分类的文章

控制器端:正确查询指定分类的文章

Laravel 9原生支持JSON字段的查询,直接用whereJsonContains方法就能精准匹配JSON数组中的值,不用复杂关联逻辑。

假设你的文章模型是App\Models\Post,要筛选分类ID为3的文章,控制器方法可以这么写:

public function categoryPosts($categoryId)
{
    // 转成字符串,匹配你JSON字段里的存储格式(示例中是字符串类型的ID)
    $targetCategory = (string)$categoryId;
    // 查询包含目标分类的文章
    $posts = \App\Models\Post::whereJsonContains('categories', $targetCategory)->get();
    
    return view('posts.list', compact('posts'));
}

注意事项:

  • 确保数据库posts表的categories字段类型是JSON(MySQL对应json列类型),如果是用字符串存的JSON格式,可改用whereRaw兼容:
    $posts = \App\Models\Post::whereRaw('JSON_CONTAINS(categories, ?)', [json_encode($targetCategory)])->get();
    
  • 如果你的JSON数组里存的是数字类型ID(比如[1,3,4]),直接传数字$categoryId就行,不用转字符串。

Blade模板:直接遍历筛选后的结果

控制器已经把符合条件的文章查出来了,模板里直接遍历$posts即可,无需二次筛选:

<div class="post-list">
    @foreach($posts as $post)
        <article class="post-item">
            <h2>{{ $post->title }}</h2>
            <p>{{ Str::limit($post->content, 150) }}</p>
        </article>
    @endforeach

    @empty($posts)
        <p>该分类下暂无文章</p>
    @endempty
</div>

若需在模板中判断单篇文章是否包含某分类

如果要在其他场景(比如文章详情页显示所属分类)判断单篇文章是否包含某个分类,可在Post模型中添加访问器,自动把JSON字段转为数组:

// app/Models/Post.php
class Post extends Model
{
    // ...其他代码

    public function getCategoriesAttribute($value)
    {
        // 把JSON字符串转为关联数组,为空时返回空数组
        return json_decode($value, true) ?? [];
    }
}

之后在模板里就能直接用in_array判断:

@if(in_array('3', $post->categories))
    <span class="badge">分类3</span>
@endif

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:33:29