我目前正在尝试保存数据透视表,但此错误不断发生。Laravel 5.4保存数据透视表
SQLSTATE [42S22]:未找到列:1054未知列在 '字段列表' role_role_id“(SQL:插入role_user
(role_role_id
,user_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
您是否已将此受保护的$ primaryKey ='role_id';'添加到您的角色模型中? – Maraboc
不,我宣布它为public $ primaryKey ='role_id'; –