Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

freemium's avatar

ORM Query Optimization

how can i optimize the query

 Model:App\Category=>Relation:App\SubCategory you should add with("App\SubCategory") to eager load this relation

 App\SubCategory=>Relation:App\Product you should add with("App\Product") to eager load this relation

controller

 $category=Category::with(['subCategory','subCategory.products' ])->get();

view file

@foreach($category as $cats)
	{{$cats->name}}
	@foreach($cats->subCategory as $subcat)
		{{$subcat->name}}
			<span>
				{{$subcat->product->count()}}
			</span>
	@endforeach
@endforeach
0 likes
9 replies
Snapey's avatar

optimise in what way? What is wrong with what you have?

Snapey's avatar

suggested improvements

Category model

   public function subCategories(){
        return $this->hasMany(SubCategory::class);
    }

   public function products(){
        return $this->hasMany(Product::class);
    }

 $categories=Category::with('subCategories.products')->get();


@foreach($categories as $category)
	{{$category->name}}
	@foreach($category->subCategories as $subcat)
		{{$subcat->name}}
			<span>
				{{$subcat->products->count()}}
			</span>
	@endforeach
@endforeach

Pay attention to giving things plural names that return more than one result

freemium's avatar

it works perfectly but result n+1 query for category and product

freemium's avatar
Illuminate\Database\Eloquent\Collection {#1544 ▼
  #items: array:3 [▼
    0 => App\Category {#1726 ▼
      #fillable: array:2 [▶]
      #connection: "mysql"
      #table: "categories"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:5 [▶]
      #original: array:5 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "subCategory" => Illuminate\Database\Eloquent\Collection {#1717 ▼
          #items: array:1 [▼
            0 => App\SubCategory {#1739 ▼
              #fillable: array:3 [▶]
              #connection: "mysql"
              #table: "sub_categories"
              #primaryKey: "id"
              #keyType: "int"
              +incrementing: true
              #with: []
              #withCount: []
              #perPage: 15
              +exists: true
              +wasRecentlyCreated: false
              #attributes: array:6 [▶]
              #original: array:6 [▶]
              #changes: []
              #casts: []
              #classCastCache: []
              #dates: []
              #dateFormat: null
              #appends: []
              #dispatchesEvents: []
              #observables: []
              #relations: array:1 [▼
                "products" => Illuminate\Database\Eloquent\Collection {#1763 ▼
                  #items: array:6 [▶]
                }
              ]
              #touches: []
              +timestamps: true
              #hidden: []
              #visible: []
              #guarded: array:1 [▶]
            }
          ]
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => App\Category {#1725 ▶}
    2 => App\Category {#1724 ▶}
  ]
}
Snapey's avatar

you did not follow the example, you still have subCategory for the relationship name

Please or to participate in this conversation.