【问题标题】:Cannot get children category product in Laravel无法在 Laravel 中获取儿童类别产品
【发布时间】: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


【解决方案1】:

首先,删除 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');
}

现在,如果我想获取所有子类别,即子类别及其产品,请在控制器中使用以下 sn-ps。

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')
}]);

【讨论】:

  • 谢谢。我已经尝试了上面的代码: $productsLists = Category::with(['children' => function($query) use ($categorySlug) { $query->with('products'); }])->get( );但它正在返回类别,但该类别中的产品数组为空,我在这里传递了一点 $categorySlug 它将仅获取选定的类别,即它可以是多个子类别。我已经更新了我的表结构和输出的图像马上就到了。
猜你喜欢
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多