我已经实现了laravel-permission来使用UUID主键来自定义我的模型。然后,我创建了一个播种机:
$viewemployee = Permission::create(['id' => Str::uuid(), 'name' => 'view employee']);
$A = Role::create(['id' => Str::uuid(), 'name' => 'A']);
但是,当我尝试使用以下方式将权限分配给角色时:
$A->givePermissionTo($viewemployee);
当我运行种子时,它显示出这样的错误
ErrorException 非法偏移类型 在vendor / laravel / framework / src / Illuminate / Database / Eloquent / Relations / Concerns / InteractsWithPivot> Table.php:139
然后,我尝试了另一种分配方法:
$viewemployee->assignRole($A);
但是,它显示了另一个错误:
Illuminate \ Database \ QueryException SQLSTATE [23000]:违反完整性约束:1452无法添加或更新子行:外键约束失败(
db
。role_has_permissions
,CONSTRAINTrole_has_permissions_role_id_foreign
外部密钥(role_id
)在删除级联上的引用roles
(id
)(SQL:插入role_has_permissions
(permission_id
,role_id
)值(8f98272b-cbc3-459b-ab23 -fc8fa86dd199,0))
我已经正确地遵循了有关UUID和扩展的文档,但是我仍然无法弄清我错过了什么,因此无法运行种子。
role
和permission
数据已成功插入,尝试插入到role_has_permissions
数据透视表时似乎遇到了麻烦。
这是我对permissions
,roles
和role_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');
});
答案 0 :(得分:0)
您需要将Str::uuid()
强制转换为字符串(string)Str::uuid()
$viewemployee = Permission::create(['id' => (string)Str::uuid(), 'name' => 'view employee']);
否则,ID的Permission
将是一个UUID对象,而不是UUID字符串。