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;
}
在上面的代码segement我想
attach
的user_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
,约束role_user_role_id_foreign
外键(role_id
)参考roles
(id
)ON DELETE CASCADE)(SQL:INSERT INTOrole_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
表的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句