【问题标题】:Group by relation laravel按关系分组 laravel
【发布时间】:2018-12-02 09:51:07
【问题描述】:

我有模型类别和产品,模型类别有2个关系:

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

public function parent()
{
    return $this->belongsTo(self::class, 'parent_id')->withoutGlobalScope('active');
}

和型号产品有:

public function category()
{
    return $this->belongsTo(Category::class);
}

我需要带有类别的 groupBy 产品,我有代码:

$products = Product::with('category')->whereHas('category', function ($query) 
          {
            $query->where('parent_id', null); //for main categories
        });

在刀片中我分组:

@forelse($products->groupBy('category.title') as $title => $prods)

如何检查父类别中的产品是否为空并使用父类别标题编写子类别中的产品?现在我得到空结果..

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    不要在视图中设置 groupBy...试试这个:

    $products = Product::with('category')->whereHas('category', function ($query) 
          {
            $query->where('parent_id', null); //for main categories
          })
    ->get()
    ->groupBy('category.title');
    

    也许您还必须执行该查询的相反操作:

    $categories = Category::withoutGlobalScope('active')
                 ->where('parent_id',null)
                 ->with('products')
                 ->get();
    

    记得添加产品 hasMany 与 Category 模型的关系

    【讨论】:

      猜你喜欢
      • 2016-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2021-07-14
      相关资源
      最近更新 更多