如何使用attach函数将用户id和角色id附加到laravel中的pivot表?

cgyqldqp  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(250)

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;
}
在上面的代码段我正在尝试 `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 )删除时(sql:insert-into) 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 table。

Schema::create('roles', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('display_name');
            $table->timestamps();
        });

上表为 roles table。

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 table。

zzzyeukh

zzzyeukh1#

医生说
当您使用$user->时,不应传递用于附加的用户\u id。。。
只需传递角色id:

$user->role()->attach( $role->id);
piah890a

piah890a2#

@伊姆鲁拉桑,
我马上就能看出许多问题。 $user->role()->attach(['user_id' => $user->id, 'role_id' => $role->id]); 实际上,您不必分别提供用户id和角色id,只需提供角色id,其余的由laravel负责。 $user->role()->attach($role->id); 在你身上 users 表迁移时,您正在创建一个不必要的角色字段,因为您正在定义一个多对多关系。因此,您可以取出该行和设置与roles表的关系的行。
完成所有必需的更改后,它应该可以正常工作。

相关问题