【发布时间】: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