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
export need to answer here
optimise in what way? What is wrong with what you have?
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
it works perfectly but result n+1 query for category and product
when you dd($categories)
what do you get
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 ▶}
]
}
you did not follow the example, you still have subCategory for the relationship name
Please sign in or create an account to participate in this conversation.