0
私の現在のプロジェクトでは、User
は多くの場合Organisations
に参加することができます。逆の場合も同様です。多対多の関係の例です。現在未確認のユーザー数(ユーザーテーブルのVerified
列が0の場合)の数をカウントしようとしています。Laravel where多対多関係に数える
マイ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
モデル:
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');
}
/**
* 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());
は、10
が実際にある場合にのみ1
と表示されます。私の関係を間違って構成していますか?