违反完整性约束:1048列"user_id"不能为null分配角色时发生错误(Laravel 5.3) [英] Integrity constraint violation: 1048 Column 'user_id' cannot be null error occurs when assigning roles (Laravel 5.3)
问题描述
我正在尝试从名为roles
表中为用户分配角色.
I'm trying to assign a role for a user from my users
and roles
table in a new table called `role_users'.
Role.php模型
class Role extends Model{
public function users(){
return $this->belongsToMany('App\User','role_users', 'role_id', 'user_id');
}
}
User.php模型
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function roles(){
return $this->belongsToMany('App\Role', 'role_users', 'user_id', 'role_id');
}
}
我一直从我的 AccountController.php
$roleuser = new User;
$user_superadmin = Role::where('role_desc', 'Superadmin')->first();
$roleuser->roles()->attach($user_superadmin); /*this line specifically*/
我有Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into 'role_users' ('role_id', 'user_id') values (1, ))
. users table
已经更新,并且user_id
已经保存到数据库中.
I'm having Integrity constraint violation: 1048 Column 'user_id' cannot be null (SQL: insert into 'role_users' ('role_id', 'user_id') values (1, ))
. The users table
is already updated and the user_id
has already been saved to the database.
有人可以帮助我吗?我一定忽略了一些重要的东西.
Can someone help me? I must have overlooked some important stuff.
推荐答案
这里的问题是您没有将角色附加到任何现有用户,而只是运行:
The problem here is that you don't attach role to any existing user, you just run:
$roleuser = new User;
创建未保存到数据库的用户对象.
to create user object that is not save to database.
您应该这样做:
$roleuser = User::find(1); // find user with id 1
$user_superadmin = Role::where('role_desc', 'Superadmin')->first();
$roleuser->roles()->attach($user_superadmin); /*this line specifically*/
或
$roleuser = User::create(['name' => 'Sample user']); // create sample user
$user_superadmin = Role::where('role_desc', 'Superadmin')->first();
$roleuser->roles()->attach($user_superadmin); /*this line specifically*/
您也不应该在这里使用$roleuser
变量,因为它显然是$user
You should also don't use $roleuser
variable here, because it's obviously $user
这篇关于违反完整性约束:1048列"user_id"不能为null分配角色时发生错误(Laravel 5.3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!