[英]UUID Spatie/Laravel-Permission SyncPermission Not Working
我在带有 Laravel 框架的 posgtre sql 中使用 uuid 作为 id,我已经更改了配置 permission.php
'model_morph_key' => 'model_uuid',
这是我的榜样
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Role as SpatieRole;
use App\Traits\Uuid;
class Role extends SpatieRole
{
use Uuid;
protected $primaryKey = 'id';
public $incrementing = false;
protected $keyType = 'string';
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'id' => 'string'
];
}
这是我的权限模型
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Spatie\Permission\Models\Permission as SpatiePermission;
use App\Traits\Uuid;
class Permission extends SpatiePermission
{
use Uuid;
protected $primaryKey = 'id';
public $incrementing = false;
protected $keyType = 'uuid';
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'id' => 'string'
];
}
在我的控制器中
public function setRolePermission(Request $request, $role)
{
//select role based role name
$role = Role::findByName($role);
$role->syncPermissions($request->permission);
return redirect()->back()->with(['success' => 'Permission to Role Saved!']);
}
当我使用方法 sycnPermission 时返回这样的错误
inner join "role_has_permissions" on "roles"."id" = "role_has_permissions"."role_id" where "role_has_permissions"."permission_id" in (1, 5, 8, 9, 14, 6354))
这个 (1, 5, 8, 9, 14, 6354)) 实际上是 uuid 数据类型。 但它总是知道作为整数数据类型。
为了解决这个问题,我做了两件事......
1.在项目中创建权限和角色模型,并从 Spatie 包扩展,添加$keyType和$primaryKey属性和特征Uuid 。
应用\\模型\\角色.php
<?php
namespace App\Model;
use App\Traits\Uuid;
use Spatie\Permission\Models\Role as SpatieRoles;
class Role extends SpatieRoles
{
use Uuid;
protected $keyType = 'string';
protected $primaryKey = 'id';
}
应用\\模型\\权限 .php
<?php
namespace App\Model;
use App\Traits\Uuid;
use Spatie\Permission\Models\Permission as SpatiePermission;
class Permission extends SpatiePermission
{
use Uuid;
protected $keyType = 'string';
protected $primaryKey = 'id';
}
2.将config/permission.php 中的权限配置更改为在您创建的新模型中引用。
'models' => [
/*
* When using the "HasPermissions" trait from this package, we need to know which
* Eloquent model should be used to retrieve your permissions. Of course, it
* is often just the "Permission" model but you may use whatever you like.
*
* The model you want to use as a Permission model needs to implement the
* `Spatie\Permission\Contracts\Permission` contract.
*/
'permission' => \App\Model\Permission::class,
/*
* When using the "HasRoles" trait from this package, we need to know which
* Eloquent model should be used to retrieve your roles. Of course, it
* is often just the "Role" model but you may use whatever you like.
*
* The model you want to use as a Role model needs to implement the
* `Spatie\Permission\Contracts\Role` contract.
*/
'role' => \App\Model\Role::class,
],
现在,模型将理解带有字符串的 UUID 而不是整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.