Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel count number of rows in has many relationship

How can I count the number of rows in a has many relationship.

The database is set up like this for example:

users:
user_id

files:
id,
name

visitors:
id,
file_id

I want to get the collective TOTAL number of visitors for every file that belongs to a certain user.

My current code is this:

$visitors = Auth::user()->files()->with('Visitors')->get();
$visitors = $visitors->count('visitor.id');

But that only returns the total amount of files, not the total amount of visitors.

like image 765
Muggles Avatar asked Dec 11 '25 01:12

Muggles


1 Answers

Since you have cascade relations:

User hasMany File hasMany Visitor

the easiest way to work with User - Visitor relation will be hasManyThrough:

// User model
public function visitors()
{
  return $this->hasManyThrough('Visitor', 'File');
}

Then all you need to get user's all files visitors' count is:

$user->visitors()->count();
like image 138
Jarek Tkaczyk Avatar answered Dec 13 '25 14:12

Jarek Tkaczyk