2017-07-26 242 views
1

我目前正在尝试保存数据透视表,但此错误不断发生。Laravel 5.4保存数据透视表

SQLSTATE [42S22]:未找到列:1054未知列在 '字段列表' role_role_id“(SQL:插入role_userrole_role_iduser_id)值(1,1))

我不知道为什么role_role_id是双状态

这里是我的模型

角色

public function users() 
{ 
    return $this->belongsToMany(User::class); 
} 

用户

public function roles() 
{ 
    return $this->belongsToMany(Role::class); 
} 

控制器

$user = new User([ 
      'name'   => $request->get('username'), 
      'email'   => $request->get('email'), 
      'password'  => $request->get('password'), 
      'role_id'   => $request->get('role_id'),   
     ]); 

     $user->save(); 

     $role = Role::find(1); 
     $role->users()->save($role); 

迁移

Schema::create('users', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('name'); 
     $table->string('email')->unique(); 
     $table->string('password'); 
     $table->string('role_id'); 
     $table->rememberToken(); 
     $table->timestamps(); 
    }); 



Schema::create('roles', function (Blueprint $table) { 
      $table->increments('role_id'); 
      $table->string('role'); 
      //Required 
      $table->string('created_by'); 
      $table->string('updated_by'); 
      $table->string('is_active'); 
      $table->timestamps(); 
     }); 

     Schema::create('role_user', function (Blueprint $table) { 
      $table->integer('role_id'); 
      $table->integer('user_id'); 
      $table->primary(['role_id', 'user_id']); 
     }); 

P.S.我只是跟着laravel https://laravel.com/docs/5.4/eloquent-relationships#the-save-method

+0

您是否已将此受保护的$ primaryKey ='role_id';'添加到您的角色模型中? – Maraboc

+0

不,我宣布它为public $ primaryKey ='role_id'; –

回答

1

的雄辩文档对于许多一对多你应该使用attach()方法:

$user = User::create($request->all()); 
$user->roles()->attach(1); 

另外,更改此:

$table->increments('role_id'); 

到:

$table->increments('id'); 

并删除此行:

$table->primary(['role_id', 'user_id']); 

然后重新创建表格。对于数据透视表外键,primary不起作用。

+0

尝试过但仍然发生 (2/2)QueryException SQLSTATE [42S22]:未找到列:1054'字段列表'中的未知列'role_role_id'(SQL:插入到'role_user'('role_role_id','' user_id')values(2,17)) –

+0

我已经删除,但仍然这个“列未找到role_role_id”正在不停地来,我已经迁移刷新和作曲家转储自动加载,但没有发生 –

+0

@MartneyAcha请阅读更新的答案。 –