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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With