按关系分组

I have Model Category and products, Model Category have 2 relations:

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

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

And model Product have:

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

I need groupBy products with category, I have code:

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

And in blade I groupBy:

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

How I can check if in parent categories products is empty and write products from child categories with parent category title? Now I get empty results..

Don't make the groupBy in the view... try this:

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

Also maybe you must do the reverse of that query:

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

Remember to add the products hasMany relation to the Category model