简体   繁体   中英

Laravel Eloquent relation between models

I need help with querying the result of relation between models. Two models are defined, User and Role model.

User:

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;
}

Role:

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;
}

Also, a pivot table called role_users is defined. In the roles database several roles are pre-defined by seeding (Admin, Editor, Author).

I want to query the users by its roles, for example,

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

where in roles database the id of editor is 2. I got the error

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

How to solve this? Note: I'm using Laravel 5.6 and new to Laravel and framework. I tried to refer to docs but it confused me.

Thanks in advance.

You have to use whereHas(..) :

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

@devk是正确的,但是这里您有另一种按角色获取用户数据的方法。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM