Laravel 8:Filter/show 数据在 blade 视图中,数组保存在数据库中

Laravel 8: Filter/show data on blade view with array saved on db

我有一个名为“products”的 table,其中包含一些数据和一个名为“category”的列,其中包含随机类别名称。我试图在我的 blade 视图中查询它,并且数据显示完美。现在我有另一个 table 称为“类别”,其中包含指定类别的数组示例:[“书”、“衬衫”等。]

ProductContoller.php

public function index($subdomain) {

     //Table which has products data
     $products = DB::table('products')->get();

     //Table which has array saved data
     $categories = DB::table('categories')->get();

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

现在我要做的是过滤与“类别”中指定的类别相匹配的产品 table 并隐藏所有其他不匹配的产品。

请帮忙,任何建议将不胜感激。

我会选择这样的东西:

$categories = ['Book', 'Shirt'];

Product::query()->whereHas('category', function (Builder $query) use ($categories): void {
    $query->whereIn('name', $categories);
})->get();

使用Eloquent's whereHas function

或者:

Product::all()->filter(function (Product $product) use ($categories): bool  {
    return in_array($product->category->name, $categories);
});

使用Collection's filter function

假设您使用的是模型和关系。