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 和框架的新手。我试图参考文档,但它让我感到困惑。

提前致谢。

开发者

你必须使用whereHas(..)

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章