[英]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.