Getting an error when associating role to a user for one to many relationship

帅比萌擦擦* 提交于 2021-02-10 16:14:55

问题


I have a one to many relationship between users and roles. I am unable to associate a role to a user while saving or updating a user, as its throwing me an error while saving the model. Please spare some time to have a look below.

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 04:44:19 where id = 3)

  • Database Structure
Users
----------
* id
* name
* email
* password
* role_id
* created_at

Roles
----------
* id
* name
* slug
* created_at
  • User Model
public function role() {
    return $this->belongsTo(Role::class);
}
  • Role Model
public function users() {
    return $this->hasMany(User::class);
}
  • User Controller
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 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');
}

来源:https://stackoverflow.com/questions/65948353/getting-an-error-when-associating-role-to-a-user-for-one-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!