【问题标题】:Illegal offset type when assigning Permission into Role in spatie/laravel-permission using UUID使用 UUID 将权限分配给 spatie/laravel-permission 中的角色时的非法偏移类型
【发布时间】:2020-11-14 22:47:17
【问题描述】:

我已经实现laravel-permission 来使用 UUID 主键自定义我的模型。然后我创建了一个播种机:

$viewemployee = Permission::create(['id' => Str::uuid(), 'name' => 'view employee']);
$A = Role::create(['id' => Str::uuid(), 'name' => 'A']);

但是,当我尝试使用以下方式为角色分配权限时:

$A->givePermissionTo($viewemployee);

运行种子时出现这样的错误

错误异常 非法偏移类型 在供应商/laravel/framework/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithPivot>Table.php:139

然后,我尝试了另一种分配方法:

$viewemployee->assignRole($A);

但是,它显示另一个错误:

照亮\数据库\查询异常 SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败(db.role_has_permissions,CONSTRAINT role_has_permissions_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (@987654330 @) ON DELETE CASCADE) (SQL: 插入role_has_permissions (permission_id, role_id) 值(8f98272b-cbc3-459b-ab23-fc8fa86dd199, 0))

我已正确遵循有关 UUID 和扩展的文档,但我仍然无法弄清楚我错过了什么,因此我无法运行我的种子。

rolepermission 数据插入成功,尝试插入role_has_permissions 数据透视表时似乎遇到了问题。

这是我对permissionsrolesrole_has_permissions 表的迁移:

Schema::create($tableNames['permissions'], function (Blueprint $table) {
      $table->uuid('id');
      $table->string('name');
      $table->string('guard_name');
      $table->timestamps();

      $table->primary('id');
});

Schema::create($tableNames['roles'], function (Blueprint $table) {
     $table->uuid('id');
     $table->string('name');
     $table->string('guard_name');
     $table->timestamps();

     $table->primary('id');
});

Schema::create($tableNames['role_has_permissions'], function (Blueprint $table) use ($tableNames) {
    $table->uuid('permission_id');
    $table->uuid('role_id');

    $table->foreign('permission_id')
        ->references('id')
        ->on($tableNames['permissions'])
        ->onDelete('cascade');

    $table->foreign('role_id')
        ->references('id')
        ->on($tableNames['roles'])
        ->onDelete('cascade');

    $table->primary(['permission_id', 'role_id'], 'role_has_permissions_permission_id_role_id_primary');
});

【问题讨论】:

  • 是否有相应的 spatie 迁移?你能分享一下你用于 role_has_permissions 表的迁移吗?
  • @KurtFriars 是的,所有迁移都成功运行,并且他们将uuid 作为主键而不是大增量,我在我的问题中添加了我的permissionsrolesrole_has_permissions 迁移

标签: php mysql laravel laravel-permission


【解决方案1】:

您需要将Str::uuid() 转换为字符串(string)Str::uuid()

$viewemployee = Permission::create(['id' => (string)Str::uuid(), 'name' => 'view employee']);

否则 ID 的 Permission 将是 UUID 对象而不是 UUID 字符串。

【讨论】:

  • 错误消息中的 SQL 显示 UUID 正在正确发送到数据库引擎。
  • @miken32 确实如此,因为insert 将投射它。但是模型会将 UUID 对象保留在 ID 中,因为它不会刷新数据库中的属性。但是,当加载关系时,Laravel 会期望一个字符串,但会得到一个对象。
猜你喜欢
  • 2022-10-20
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-17
  • 2020-11-01
  • 2018-07-05
  • 2019-05-26
相关资源
最近更新 更多