问题
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: updateusers
setrole_id
= [3],users
.updated_at
= 2021-01-29 04:44:19 whereid
= 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