这是我在错误发生之前正在做的
我正在尝试从我的users
和roles
表中为用户分配角色,称为" coles_users"。
角色.php模型
class Role extends Model{
public function users(){
return $this->belongsToMany('AppUser','role_users', 'role_id', 'user_id');
}
}
user.php模型
class User extends Model implements Authenticatable
{
use IlluminateAuthAuthenticatable;
public function roles(){
return $this->belongsToMany('AppRole', '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
已保存到数据库。
有人可以帮我吗?我一定忽略了一些重要的东西。
这里的问题是您不将角色附加到任何现有用户,只需运行:
$roleuser = new User;
创建不能保存到数据库的用户对象。
您应该做这样的事情:
$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
您无法将关系附加到非现有用户。尝试首先创建用户:
$roleuser = User::create(['name' => 'John']); // Instead of new User;
或从db获取用户:
$roleuser = User:find(1);
我在使用Laravel 9时遇到了相同的问题。您应该在添加权限之前创建用户。
$user = new User();
然后采取行动最后保存您的用户
$user->save();