【问题标题】:Integrity constraint violation: 1048 Column 'user_id' cannot be null error occurs when assigning roles (Laravel 5.3)完整性约束违规:1048 Column 'user_id' cannot be null 分配角色时发生错误(Laravel 5.3)
【发布时间】:2017-05-05 20:47:39
【问题描述】:

Here's what I was doing before the error occurred

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

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

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

【问题讨论】:

  • 我的模式感觉很刺痛。 A User 不应该有很多角色,而不是属于吗?
  • 你的意思是用 hasMany 代替?是的,我昨晚正在使用那个。但我收到Call to undefined method Illuminate\Database\Query\Builder::attach() 错误。它应该在双方都有一个 belongsToMany 关系。
  • 这没有意义。在关系中,模型 A 属于模型 B,模型 B 有许多模型 A。让他们都属于每个人似乎违反了原则。
  • 嗯。这一定是因为我正在使用一个数据透视表,而这恰好是多对多关系所必需的。但是对于用户角色关系,它只是一对多,所以我真的不需要数据透视表,只需将其直接保存到我的users 表即可。一定是为什么它看起来如此矛盾?
  • 可能是的。这更有意义

标签: php mysql laravel migration roles


【解决方案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

【讨论】:

  • 我知道。呵呵。但我昨晚使用 $user 作为变量,但出现错误。我尝试更改它,然后它就起作用了..直到我收到此错误。
  • 这成功了!我在运行最后两行之前使用了$user = User::find($user_id);,因为我已经有一个用户注册到数据库。
【解决方案2】:

您不能将关系附加到非现有用户。尝试先创建用户:

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

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

$roleuser = User:find(1);

【讨论】:

    猜你喜欢
    • 2016-11-07
    • 2020-01-31
    • 2021-03-22
    • 2019-02-12
    • 2019-10-25
    • 2022-10-18
    • 2022-11-04
    • 2020-04-22
    • 1970-01-01
    相关资源
    最近更新 更多