w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Counting related rows in a child table

You can use helper relation for this, if you'd like to use Eloquent instead of manual joins:

// Request model
public function contactsCount()
    return $this->hasOne('Contact')->selectRaw('request_id, count(*)
as aggregate')->groupBy('request_id');

public function getContactsCountAttribute()
    if ( ! array_key_exists('contactsCount', $this->relations))

    return $this->getRelation('contactsCount')->aggregate;

The same would go for Contact model towards History model.

For counting far relation (Request -> History) you can use hasManyThrough relation with a little adjustment.

This way you can eager load those aggregates for multiple models without n+1 issue, nice and easy:

$requests = Request::with('contactsCount',
// 1 query for reuqests, 1 query for contacts count and 2 queries for

// example output
$requests->first()->contactsCount; // 17
$requests->first()->contacts->first()->historyCount; // 5

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.