Search code examples
laravellaravel-8has-many

Laravel HasMany relationships count


I have a user model with hasMany relationship.

User has many unreviewed files and im trying to get the total number of unreviewed files. this is how i did it. i just wonder if there is a better way.

    $users = User::families()->whereHas('unreviewedcovidfiles')->withCount('unreviewedcovidfiles')->get();
    $totalfiles = 0;
    foreach($users as $user){
        $totalfiles += $user->unreviewedcovidfiles_count;
    }
    return $totalfiles;

Solution

  • Assume that you have a user relationship on unreviewedcovidfiles model.

    You can get the count from the model of unreviewedcovidfiles directly and filter the users by tenant via whereHas method:

    $totalfiles  = Unreviewedcovidfile::whereHas('user', function($query){
        $query->families();
    })->count();
    

    https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence

    Alternatively, use the sum method for the collection:

    $users = User::families()->whereHas('unreviewedcovidfiles')->withCount('unreviewedcovidfiles')->get();
    $totalfiles = $users->sum('unreviewedcovidfiles_count');
    

    https://laravel.com/docs/8.x/collections#method-sum