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

Laravel 8:基于数据库存储的分类数组在Blade视图过滤展示产品数据

实现方案

我们可以直接在SQL查询阶段过滤产品,避免拉取冗余数据,性能最优,修改后代码如下:

public function index($subdomain) {
    // 1. 先取出允许的分类列表
    // 假设categories表存储分类数组的字段为allowed_categories,且全局只有一条分类配置记录
    $allowedCategoryJson = DB::table('categories')->value('allowed_categories');
    $allowedCategories = json_decode($allowedCategoryJson, true);

    // 2. 查询时直接过滤符合分类要求的产品
    $products = DB::table('products')
        ->whereIn('category', $allowedCategories)
        ->get();

    $categories = DB::table('categories')->get();

    return view('products.index', compact('products', 'categories'));
}

特殊场景适配

  • 如果你的categories表是单条记录存一个分类(不是一条存整个数组),把取允许分类的代码替换为:
    $allowedCategories = DB::table('categories')->pluck('category_name')->toArray();
    
  • 如果你已经需要全量拉取产品做其他处理,可以在集合阶段过滤:
    $products = DB::table('products')->get()->whereIn('category', $allowedCategories);
    

注意事项

  • 请把代码中的allowed_categories、category_name替换为你表中实际对应的字段名
  • 若存在多套分类配置,在查询categories表时加对应的where条件筛选对应记录即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 15:54:00