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
相关产品推荐
相关产品推荐

