簡體   English   中英

Laravel where 依賴多對多關系

[英]Laravel whereHas count on Many-to-Many relationship

在我當前的項目中,一個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 我是否錯誤地構建了我的關系?

whereHas()將返回01 它只是告訴您是否存在這樣的用戶。

解決方案要簡單得多:

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

如果您只需要計數:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM