Integrity constraint violation: 1048 Column 'user_id' cannot be null 分配角色时出现错误 (Laravel 5.3)

Integrity constraint violation: 1048 Column 'user_id' cannot be null error occurs when assigning roles (Laravel 5.3)

我正在尝试为我的 usersroles table 中的用户分配一个名为“role_users”的新 table 中的角色.

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 已保存到数据库。

有人可以帮助我吗?我一定是忽略了一些重要的东西。

您不能将关系附加到不存在的用户。先尝试创建用户:

$roleuser = User::create(['name' => 'John']); // Instead of new User;

或者从数据库中获取用户:

$roleuser = User:find(1);

这里的问题是您没有将角色附加到任何现有用户,您只是 运行:

$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