如何检查用户是否具有一对一关系的角色?

How can I check if the user has a role for one to one relationship?

我有一个包含用户和角色模型的应用程序,它们之间是一对一的关系。如何检查用户是否具有角色。我收到 SQLSTATE[42S22] 错误。

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from roles where roles.user_id = 1 and roles.user_id is not null and name = client limit 1)

Users
---------------
* id
* name
* email
* password
* role_id
* created_at

Roles
---------------
 * id
 * name
 * slug
 * created_at
public function role() 
{
    return $this->hasOne(Role::class);
}

public function hasRole(string $role) 
{
    if ($this->role()->where('name', $role)->first()) {
        return true;
    }
    return false;
}
public function users() 
{
    return $this->belongsTo(User::class);
}

你需要反转关系。用户有 1 个角色,角色有很多用户

角色:

public function users() 
{
    return $this->hasMany(User::class);
}

用户:

public function role() 
{
    return $this->belongsTo(Role::class);
}

这是一对多关系。请参阅文档:https://laravel.com/docs/8.x/eloquent-relationships#one-to-many