简体   繁体   English

Laravel count 中的行数有很多关系

[英]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.但这仅返回文件总数,而不返回访问者总数。

Since you have cascade relations:由于您有级联关系:

User hasMany File hasMany Visitor

the easiest way to work with User - Visitor relation will be hasManyThrough :处理User - Visitor关系的最简单方法是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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM