【发布时间】:2020-07-26 08:22:27
【问题描述】:
RegisterController.php
protected function create(array $data)
{
$role = Role::where('name', 'customer')->first();
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'remember_token' => Str::random(60),
]);
$user->role()->attach(['user_id' => $user->id, 'role_id' => $role->id]);
return $user;
}
在上面的代码段中,我正在尝试将
attachuser_id和role_id添加到pivot表中,该表在 用户注册时被命名为role_user
User.php
public function role()
{
return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}
上面的代码段是
User和Role的关系
我遇到的错误。
SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(
deal_ocean.role_user,CONSTRAINTrole_user_role_id_foreignFOREIGN KEY (role_id) REFERENCESroles(id) ON DELETE CASCADE) (SQL: 插入role_user(role_id,user_id) 值(5, 5), (4, 5))
供参考:以下是我创建的表格。
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('role_id')->default(4);
$table->string('name');
$table->string('email')->unique();
$table->string('photo')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->longText('cartitems')->nullable();
$table->longText('wishlist')->nullable();
$table->unsignedBigInteger('discount')->default(0);
$table->rememberToken();
$table->timestamps();
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
});
上面的表格是
users的表格。
Schema::create('roles', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('display_name');
$table->timestamps();
});
上面的表格是
roles的表格。
Schema::create('role_user', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('role_id');
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->timestamps();
});
上面的表格是
role_user的表格。
【问题讨论】:
-
当你有一个单独的 user_role 表来管理关系时,你为什么要在你的用户表中
$table->unsignedBigInteger('role_id')->default(4);?
标签: php sql laravel foreign-keys pivot