Laravel Eloquent模型之间的关系

时间:2018-06-07 03:40:34

标签: php laravel eloquent

我需要帮助查询模型之间的关系结果。定义了两个模型,用户角色模型。

用户:

public function roles()
{
    return $this->belongsToMany('App\Role', 'role_users');
}

public function hasAccess(array $permissions) : bool
{
    foreach ($this->roles as $role) {
        if ($role->hasAccess($permissions)) {
            return true;
        }
    }

    return false;
}

public function inRole(string $slug)
{
    return $this->roles()->where('slug', $slug)->count() == 1;
}

作用:

public function users()
{
    return $this->hasMany('App\User', 'role_users');
}

public function hasAccess(array $permissions) : bool
{
    foreach ($permissions as $permission) {
        if ($this->hasPermission($permission)) {
            return true;
        }
    }

    return false;
}

private function hasPermission(string $permission) : bool
{
    return $this->permissions[$permission] ?? false;
}

此外,还定义了名为role_users的数据透视表。在roles数据库中,通过种子设定(管理员,编辑者,作者)预先定义了几个角色。

我想按用户的角色查询用户,例如

$editors = App\User::roles(2)->orderBy('name', 'asc')->get()

roles数据库中,编辑器的id为2.我收到了错误

PHP Deprecated:  Non-static method App/User::roles()

如何解决这个问题?注意:我使用的是Laravel 5.6和Laravel和框架的新手。我试图引用docs,但这让我很困惑。

提前致谢。

2 个答案:

答案 0 :(得分:1)

您必须使用whereHas(..)

$editors = \App\User::whereHas('roles', function ($q) {
    $q->where('id', 2);
})->orderBy('name', 'asc')->get()

答案 1 :(得分:0)

@devk是正确的,但在这里您可以通过另一种方式获取用户的数据。

\App\Role::where('id', 2)->with('users')->get();