mardi 23 août 2016

Laravel hasMany relation count

There are many Categories(Category.php) on my index site, which has many Boards(Board.php). A Board can have many Topics(Topic.php), and a Topic can have many Replies (Reply.php).

I want to fetch the number of replies of the current board, possibly with eager loading.

I have a way, but it executes too many queries. I create a post_count attribute, then I iterate over every topic and gather number of replies. Is there a way to select all replies from the current board?

public function getPostCountAttribute()
{
    $count = 0;
    foreach ($this->topics()->withCount('replies')->get() as $topic) {
        $count += $topic->replies_count;
    }
    return $count;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire