2016-05-15 142 views
0

在我目前的項目中,User可能會加入很多Organisations,反之亦然 - 多對多關係的一個例子。我試圖計算當前未驗證的用戶數(用戶表上的Verified列等於0)。Laravel哪裏有多對多的關係

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。我是否錯誤地構建了我的關係?

回答

1

whereHas()將返回01。它只是告訴你,如果這樣的用戶存在。

的sollution簡單得多:

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

如果你只需要計數:

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