扩展Spatie角色模型,但使用其他数据库表

时间:2019-09-26 09:57:46

标签: php laravel spatie

我需要做的是扩展Spatie权限包Role模型的所有功能,但是对派生模型使用不同的表。

现在,我有一个SubscriptionPackage模型,我想模拟Role的行为,以便可以为它分配权限,然后可以将此模型分配给用户。但是我也想保持角色模型不变。

我尝试扩展“是”,但是当我创建新的SubscriptionPackage时,尽管在派生模型中指定了表,但仍在角色表中创建了新记录,而不是subscription_packages表。如下图所示

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Permission; // This extends from Spatie\Permission\Models\Permission
use Spatie\Permission\Models\Role as SpatieRole;



class SubscriptionPackage extends SpatieRole
{
    //
    protected $guarded = ['id'];

    protected $table = 'subscription_packages';


    /**
     * The permissions that belong to the package.
     */
    public function packagePermissions()
    {
        return $this->belongsToMany(Permission::class);
    }

}

使用上面的代码,当我创建一个新的SubscriptionPackage时,该记录应该插入subscription_packages表中,但在这种情况下,它会转到角色表中。 任何有关如何做到这一点的指针将受到高度赞赏。

2 个答案:

答案 0 :(得分:1)

如果您查看Role源代码,可以在// Index array2 by the 'name' value $array2 = array_column($array2, null, "name"); foreach ( $array1 as $element) { // Use the propertyName value from array1 to find details echo $array2[$element->propertyName]->customFieldId ?? "Not found".PHP_EOL; } 方法内进行:

__construct

因此,如果您希望您的public function __construct(array $attributes = []) { $attributes['guard_name'] = $attributes['guard_name'] ?? config('auth.defaults.guard'); parent::__construct($attributes); $this->setTable(config('permission.table_names.roles')); // <-- HERE IS THE PROBLEM! } 在正确的表中写入其记录,则必须重写此行为,如下所示:

SubscriptionPackage

答案 1 :(得分:0)

我认为你不能。 Spatie已经有5个表,并且仅从中获取数据。但是,如果要进行更改,则必须在模型中使用表名和列名进行更改