将角色与用户关联以获得一对多关系时出现 SQLSTATE [22007] 错误

Getting an SQLSTATE[22007] error when associating role to a user for one to many relationship

我在 usersroles 之间有一个一对多的关系。我有三个角色 administratoremployeeclient。我无法将用户与角色相关联。

示例: 当我使用角色 administrator 更新用户时,我成功地编辑角色并将其保存到 employeeclient,但是当我单击保存时默认角色值保持不变,即administrator,它抛出一个 SQLSTATE[22007] 错误。

请抽空看看下面。

Illuminate\Database\QueryException SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect integer value: '[3]' for column management.users.role_id at row 1 (SQL: update users set role_id = [3], users.updated_at = 2021-01-29 05:08:12 where id = 3) http://127.0.0.1:8000/backend/management/audience-management/user

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

Roles
----------
* id
* name
* slug
* created_at
public function role() {
    return $this->belongsTo(Role::class);
}
public function users() {
    return $this->hasMany(User::class);
}
public $showUserUpdationModal = false;
public $role;
public User $user;

protected $rules = [
    'user.name' => 'required|string|max:255',
    'user.email' => 'required|string|email|max:255',
    'role' => 'required',
];

public function updateUser(User $user)
{
    $this->resetValidation();
        
    $this->user = $user;
    $this->role = $user->role()->pluck('id');
    $this->showUserUpdationModal = true;
}

public function storeUser()
{
    $this->validate();
    $this->validate([
        'user.email' => 'unique:users,email,'.$this->user->id,
    ]);
    $this->user->role()->associate($this->role);
    $this->user->save();
    $this->showUserUpdationModal = false;

    $this->dispatchBrowserEvent('notify', $this->user->name.' Updated Successfully');
    $this->emit('sectionRefresh');
}

问题是您试图将 role_id 值分配给数组而不是整数。

尝试将 role_id 保存为整数角色 ID,例如:

$user->role_id = 1;
$user->save();

而不是

$user->role_id = [1];
$user->save();

编辑

基于代码,

public function updateUser(User $user)
{
    $this->resetValidation();
        
    $this->user = $user;
    $this->role = $user->role_id; //This should world now
    $this->showUserUpdationModal = true;
}