【发布时间】:2016-09-11 08:16:18
【问题描述】:
在我当前的项目中,User 可以加入许多 Organisations,反之亦然 - 多对多关系的示例。我正在尝试计算当前未验证的用户数(其中用户表上的Verified 列等于0)。
我的User 模特:
/**
* Get the organisations that the user is a part of.
*/
public function organisation()
{
return $this->belongsToMany(
Organisation::class, 'organisation_users', 'user_id', 'organisation_id'
)->withPivot(['role'])->orderBy('name', 'asc');
}
我的Organisation 模特:
/**
* Get all of the users that belong to the organisation.
*/
public function users()
{
return $this->belongsToMany(
User::class, 'organisation_users', 'organisation_id', 'user_id'
)->withPivot('role');
}
所以如果我想计算未验证用户的数量,我在Organisation 模型上有以下方法:
/**
* An organisation may have unverified users attached.
*/
public function unverifiedUsers()
{
return $this->whereHas('users', function($query) {
$query->where('verified', 0);
})->get();
}
但是,运行dd(\App\Organisation::find($org->id)->unverifiedUsers()->count()); 只显示1,而实际上应该有10。我的人际关系结构是否不正确?
【问题讨论】: