【发布时间】:2020-01-14 01:32:26
【问题描述】:
我有一个关于 laravel eloquent 的问题。
数据库表
类别:id root_id 名称
产品 ID 名称等。
product_categories id product_id category_id
所以它可能是 CategoryA 有一个子 CategoryB 而 CategoryB 本身有一个子 CategoryC。
当我点击 CategoryA 时,我想查找属于 CategoryA、CategoryB、CategoryC 的所有产品
Category Model
public function cats()
{
return $this->hasMany(Category::class);
}
public function childrenCategories()
{
return $this->hasMany(Category::class)->with('cats');
}
产品型号
public function categories()
{
return $this->belongsToMany(Category::class);
}
控制器
//首先我得到所有类别的所有id,所有级别的子类别。
$categories = Category::where('category_id',$category_id)->with('childrenCategories')->get();
$all_cat_array=array();$all_prod=array();
foreach ($categories as $category)
{
foreach ($category->childrenCategories as $childCategory) {
array_push($all_cat_array, $childCategory->id);
}
array_push($all_cat_array,$category->id);
}
//然后我得到所有产品的id
foreach ($all_cat_array as $cat)
{
if(CategoryProduct::where('category_id',$cat)->exists()) {
$prod=CategoryProduct::where('category_id',$cat)->pluck('product_id');
array_push($all_prod,$prod );
}
}
但我不想使用所有这些 foreach,因为我想优化代码。 我该怎么做才能让它更简单???
【问题讨论】:
-
CategoryA 与 CategoryB 有关系。是一对多的关系吗?
-
是的。就像:CategoryA whth id 1 没有 root_id,另一方面 CateogryB 的 root_id 是 1