【问题标题】:How can I attach the user id and role id to the pivot table in laravel using attach function?如何使用附加功能将用户 ID 和角色 ID 附加到 laravel 中的数据透视表?
【发布时间】: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;
    }

在上面的代码段中,我正在尝试将attach user_idrole_id 添加到 pivot 表中,该表在 用户注册时被命名为 role_user

User.php

public function role()
{
   return $this->belongsToMany(Role::class, 'role_user', 'user_id', 'role_id');
}

上面的代码段是UserRole的关系

我遇到的错误。

SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(deal_ocean.role_user,CONSTRAINT role_user_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (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


【解决方案1】:

根据doc

使用 $user-> 时不应传递 user_id 进行附加...

只需传递角色 id:

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

【讨论】:

    【解决方案2】:

    @ImrulHasan,

    马上,我就发现了很多问题。

    1. $user->role()->attach(['user_id' => $user->id, 'role_id' => $role->id]);

    您实际上不必分别提供用户 id 和角色 id,只需提供角色 id,laravel 会处理其余的事情。 $user->role()->attach($role->id);

    1. users 表迁移中,您正在创建一个不必要的 roles 字段,因为您正在定义多对多关系。因此,您可以取出该行以及与 roles 表设置关系的行。

    完成所有必需的更改后,它应该可以正常工作。

    【讨论】:

    • 如果我不在那里使用 role_id ......那么我不必为角色 id 使用任何外键?
    • 是的,因为你的 role_user 表会处理这个问题。它已经跟踪了 user_id 和 role_id。更多信息请参考this
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多