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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.