无法在Laravel中获取子类别产品

无法在Laravel中获取子类别产品,laravel,laravel-5,eloquent,Laravel,Laravel 5,Eloquent,当我点击父类别的任何链接时,我想获得子类别产品,现在我的关系对单个类别正常工作 我的表格结构如下: 产品: 类别: 产品类别: 我已在控制器中为其创建了一个函数: public function show($categorySlug, $subcategorySlug=null) { $category = $this->categoryRepository->findBySlug($categorySlug); $child_c

当我点击父类别的任何链接时,我想获得子类别产品,现在我的关系对单个类别正常工作

我的表格结构如下:

产品:

类别:

产品类别:

我已在控制器中为其创建了一个函数:

 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'));
    }
类别模型:

视图:

我使用以下语句获取类别和产品数据:

 @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); 
}
但我没有得到所有的儿童类别,但没有得到相关的产品。如下图所示,产品数组为空,存在一些关系问题。请帮忙解决。

输出:


首先,删除childrenProdut(),因为此函数与children()函数的作用相同

类别模型:

public function children() {
    return $this->hasMany(Category::class, 'parent_id');
}

public function products() {
    return $this->belongsToMany(Product::class, 'product_categories', 'category_id', 'product_id');
}
现在,如果我想获得所有子类,即子类别及其产品,那么在控制器中使用以下代码段

Category::with(['children' => function($query){
    //the 'children' relationship should be called within an array
    //this way you could query the relationship as the eloquent model.
    //that way you could call the 'products' relationship inside the Category relationship.
    $query->with('products')
}]);

在获取产品信息或获取所有字段值时,您是否选择了一些特定字段?您的意思是“但是我已经操纵了子类别的代码,但是我没有获取所有子类别,但是没有获取相关产品”?你能详细说明一下吗?做了什么操作,你期望得到什么结果,你实际得到什么?对不起,现在我在上面的问题中在类别存储库中添加了getChildCategories函数,但这里我没有得到所有子类别下的产品,我得到的所有子类别如图所示,但我希望该类别内的产品FindBySlug正常工作,因为这是针对单个类别的,但会出现多个类别的情况,并且这些多个类别必须有与每个类别关联的产品。@sachinkumar:我选择的是有限的FieldsHanks。我已经试过上面的代码:$productsLists=Category::with(['children'=>function($query)use($categorySlug){$query->with('products');}])->get();但它返回的是类别,但该类别中的产品数组为空,我在这里再传递一点$categorySlug,它将只获取选定的类别,也就是说,它可以是多个子类别。我已经更新了我的表结构和我现在获得的输出的图像。
Category::with(['children' => function($query){
    //the 'children' relationship should be called within an array
    //this way you could query the relationship as the eloquent model.
    //that way you could call the 'products' relationship inside the Category relationship.
    $query->with('products')
}]);