I'm having some concerns with looping a Laravel model. I have 3 tables that are associated with one another, and one of them should be looped with children and show relations of the other tables as well, so what is the deal here..
I have 3 tables:
categories
- id
- parent_id = relation to the same table foreign id
- name = string
threads
- id
- category_id = relation with categories
- title
- desc
posts
- id
- category_id = to make query easier
- thread_id = relation with threads
- description
So, I want to achieve looping threw the categories model, get all models and show the json. So what am I doing.
I have in controller like:
Category::whereNull('parent_id')->with(['loopInfinite' => function ($query) {
$query->withCount('posts', 'threads');
}])->withCount('posts', 'threads')->orderBy('order')->get();
So I can get directly from a parent. And counting the loopInfinite
And loopInfinite looks like:
public function loopInfinite(): HasMany
{
return $this->hasMany(static::class, 'parent_id')->with('loopInfinite')->withCount('posts', 'threads');
}
So here, I'm getting infinite loop that works fine. But, the count will work only for the specific category, and I want that any parent will include a count of the children, but to show only first children of the parent. Any ideas how to do it? And I'm calling withCount to many times, I believe it's not the best practise in that case.