【发布时间】:2020-07-17 13:41:15
【问题描述】:
当我单击父类别的任何链接时,我想获得子类别产品,现在我的关系在单类别中正常工作,
我的表结构如下:
产品:
类别:
产品类别:
我在控制器中为此创建了一个函数:
public function show($categorySlug, $subcategorySlug=null)
{
$category = $this->categoryRepository->findBySlug($categorySlug);
$child_categories=$this->categoryRepository->getChildCategories($category->id);
if($child_categories->childrenProdut->count()==0)
{
$category=$category;
}
else{
$category=$child_categories->childrenProdut;
}
return view('site.pages.category', compact('category','child_categories'));
}
类别模型:
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
public function childrenProdut()
{
return $this->hasMany(Category::class, 'parent_id');
}
public function products()
{
return $this->belongsToMany(Product::class, 'product_categories', 'category_id', 'product_id');
}
查看:
我使用以下语句获取类别和产品数据:
@forelse($category->products as $product)
主要问题:
对于单个类别,我使用以下方法获取数据,即该类别的产品:
public function findBySlug($slug)
{
return Category::with('products')
->where('slug', $slug)
->where('menu', 1)
->first();
}
但我已经操纵了子类别的代码
public function getChildCategories($id)
{
return Category::with('children','products')->find($id);
}
但我没有获得所有子类别,但没有获得相关产品。如下图所示,产品数组为空,存在一些关系问题。请帮忙解决。
输出:
【问题讨论】:
-
您是在获取产品信息时选择某些特定字段还是获取所有字段值?
-
你是什么意思“但是我已经操纵了儿童类别的代码,但我没有获得所有子类别但没有获得相关产品”?你能详细说明和具体吗?进行了哪些操作,您期望得到什么结果以及实际得到什么?
-
对不起,现在我已经在上述问题的类别存储库中添加了 getChildCategories 函数,但这里我没有得到所有子类别下的产品,我得到了图像中的所有子类别,但我想要属于该类别的产品
-
findBySlug 有效,因为这是针对单个类别的,但有时会有多个类别,并且这些多个类别必须具有与每个类别相关联的产品。
-
@sachinkumar:我选择了有限的字段
标签: laravel laravel-5 eloquent