【问题标题】:how to display 15 product from category having multiple subcategories in random order in laravel?如何在laravel中以随机顺序显示具有多个子类别的类别中的15个产品?
【发布时间】:2021-10-16 10:28:47
【问题描述】:

我有 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;

我的输出是这样的

注意:我无法通过急切加载来做到这一点。所以,我按照简单的逻辑做了,但无法将数据传递给视图。

【问题讨论】:

  • Product::all()->unique('category_id')->slice(0, 15); 试试看
  • 谢谢!我从任何类别中获得了 15 个没有重复的独特产品。但真正的问题是如何将用户希望发送到主页的每个类别的 15 个产品发送到我在上图中提到的主页?

标签: laravel laravel-5 laravel-8 laravel-7 laravel-6


【解决方案1】:

在控制器中我做了

//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;
        
}

结果

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

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多