扩展 Spatie 角色模型但使用不同的数据库 table

Extending the Spatie Role Model but use a different database table

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

现在我有一个 SubscriptionPackage 模型,我想模拟 Role 的行为,以便可以为其分配权限,然后可以将该模型分配给用户。但我也想保持角色模型完好无损。

我试过扩展 Yes,但是当我创建一个新的 SubscriptionPackage 时,新记录是在角色 tables 中创建的,而不是 subscription_packages table 22=] 在我的派生模型中。如下图

<?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 table 但在这种情况下它会转到角色 table。 任何有关如何解决此问题的指示都将不胜感激。

我认为你做不到。 Spatie 已经有 5 tables 并且仅从中获取数据。但是,如果您想进行更改,您仍然可以使用模型中的 table 和列名进行更改

如果您查看 Role 源代码,您将在 __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 将其记录写入右侧 table,您必须像这样覆盖此行为:

public function __construct(array $attributes = [])
    {
        parent::__construct($attributes)

        $this->setTable('your_table_name'); // <-- HERE THE SOLUTION!
    }