Home > database >  Laravel HasMany relationships count
Laravel HasMany relationships count

Time:01-16

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;

CodePudding user response:

You can achieve this using hasManyThrough relationship. After defining relationship you can count simply using count() on relationship.

CodePudding user response:

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

  •  Tags:  
  • Related