【问题标题】:Laravel whereHas count on Many-to-Many relationshipLaravel whereHas 依靠多对多关系
【发布时间】: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。我的人际关系结构是否不正确?

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    whereHas() 将返回 01。它只是告诉你是否存在这样的用户。

    解决方案要简单得多:

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

    如果你只需要计数:

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

    【讨论】:

      猜你喜欢
      • 2014-01-11
      • 2014-11-29
      • 2023-03-09
      • 2018-10-18
      • 1970-01-01
      • 2011-12-11
      • 2018-06-15
      • 2018-01-22
      • 2016-02-26
      相关资源
      最近更新 更多