如何在 laravel 中以随机顺序显示具有多个子类别的类别中的 15 种产品?

how to display 15 product from category having multiple subcategories in random order in laravel?

我有 3 个表:

homepage
    order- integer
    status - boolean
    product_category_id - integer

category
    name- string
    slug- slug
    parent_id- integer

product
    name- string
    category_id- integer

当用户希望在主页中有这样的分类时

我想在主页上有 15 个类别的产品,包括随机排列的子类别的产品。到目前为止我所做的是

 //  all categories to be posted in homepage.
        $hp_categories = HomepageCategory::asc()->active()->get();

        foreach ($hp_categories as $hp_cat) {
            // array declaration
            $cat_with_subcat_arr = [];
            // category
            $product_category = ProductCategory::where('id', $hp_cat->product_category_id)->first();            
            // push category's id to array
            array_push($cat_with_subcat_arr, $product_category->id);
            // subcategories if any.
            $product_category->childrenCategoriesIds($cat_with_subcat_arr);
            
            // product from categories and subcategories via whereIn.
            $products = Product::whereIN('product_category_id', $cat_with_subcat_arr)->inRandomOrder()->limit(15)->get();
                    
            dd($products);
        }
        return $hp_categories;

我的输出是这样的

注意:我无法通过预先加载来完成。所以,我通过简单的逻辑做到了,但无法将数据传递给视图。

我在控制器中做了

//define a collection;
$hp_cats = collect();

foreach ($hp_categories as $key=>$hp_cat) {

    // array declaration
    $cat_with_subcat_arr = [];

    // category
    $product_category = ProductCategory::where('id', $hp_cat->product_category_id)->first();            
 
    // push category's id to array
            
    array_push($cat_with_subcat_arr, $product_category->id);
            
    // subcategories if any.
            
    $product_category->childrenCategoriesIds($cat_with_subcat_arr);
            
            
    // product from categories and subcategories via whereIn.
            
    $products = Product::whereIN('product_category_id', $cat_with_subcat_arr)
            ->inRandomOrder()
            ->limit(15)
            ->get();
            
            
    $hp_cats[$key] = $products;
        
}

结果

注意:我找不到答案,因此它可能不是最佳解决方案。任何帮助都适用。