2016-05-15 11 views
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と表示されます。私の関係を間違って構成していますか?

答えて

1

whereHas()0または1を返します。そのようなユーザーが存在するかどうかだけを伝えます。

sollutionははるかに簡単です:

public function unverifiedUsers() 
{ 
    return $this->users()->where('verified', 0)->get(); 
} 

あなただけの数が必要な場合:

public function unverifiedUsersCount() 
{ 
    return $this->users()->where('verified', 0)->count()->get(); 
}