Integrity constraint violation: 1048 Column 'u

2019-07-21 14:08发布

Here's what I was doing before the error occurred

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 model

class Role extends Model{  
  public function users(){
    return $this->belongsToMany('App\User','role_users', 'role_id', 'user_id');
  }
}

User.php model

class User extends Model implements Authenticatable
{
  use \Illuminate\Auth\Authenticatable;

  public function roles(){
    return $this->belongsToMany('App\Role', 'role_users', 'user_id', 'role_id');
  }    
}

I keep getting the error in this line from my AccountController.php

$roleuser = new User;
$user_superadmin = Role::where('role_desc', 'Superadmin')->first();
$roleuser->roles()->attach($user_superadmin); /*this line specifically*/

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.

2条回答
贪生不怕死
2楼-- · 2019-07-21 14:31

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.

You should rather do something like this:

$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*/

or

$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*/

You should also don't use $roleuser variable here, because it's obviously $user

查看更多
男人必须洒脱
3楼-- · 2019-07-21 14:45

You can't attach relation to non existing user. Try to create user first:

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

Or fetch user from DB:

$roleuser = User:find(1);
查看更多
登录 后发表回答