简体   繁体   中英

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;
}

Found a nice way. Even though, I'll leave this question open, if anyone finds a better way to do it.

I declared a hasManyThrough relationship, and the called the count():

Board.php:

public function replies()
    {
        return $this->hasManyThrough(Reply::class, Topic::class);
    }

And then called:

$board->replies->count()

30 queries executed (45 before).

Still, I would like to find an eager way to load the data, getting the query number down to 2 or 3 queries.

In addition to your reply you can do something like this.

 public function repliesCount() {
        return $this->replies()->selectRaw('board_id, count(*) as aggregate')
                        ->groupBy('board_id');
    }

and to use this use as below

$board->repliesCount()

Please note that you have to change query according to you.

Try it

Change

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

To

$topic_ids = $this -> topics -> pluck('id');
$reply_count = Reply::whereIn('id',$topic_ids) -> count();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM