I have the following tables
groups
- id
- title
categories
- id
- title
- parent_id
- group_id
threads
- id
- replies_count
- title
- category_id
replies
- id
- thread_id
- For each group, i display the title of the group
- For each category associated with a group, i display the title of the category, the total number of threads and replies associated with that category
- The categories table consists of children and parent categories. Therefore, when i display the title of a parent category ( a category that has children ), i want to display next to the title, the total number of threads and replies that are associated with its children categories.
For the total number of threads for a parent category i have the following relationship and i load the count
protected $withCount = ['parentThreads']
public function parentThreads()
{
return $this->hasManyThrough(
Thread::class,
Category::class,
'parent_id',
'category_id'
);
}
For the total number of replies associated with a group i have the following code
public function getParentRepliesCount() {
return $this->parentThreads()->sum('replies_count');
}
The problem is that in the blade view then i have to call this accessor which makes a query ( which is a bad practice, if i'm not mistaken )
<p> {{ $category->parent_replies_count }} </p>
My question is if there is a better alternative ?
Also i'd like you ask whether it is a bad practice to have hierarchy in the same table, because currently i have a categories table which consists of parent and children, and in the Category model i end up with several methods that have parent and **children prefix **