You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The reason of this behavior is in overriding of method getTable in Spatie\Permission\Models\Role.
When extending Illuminate\Database\Eloquent\Model:
echo \App\Models\Department::withCount('children')->toSql();
/**
SELECT `roles`.*, (
SELECT COUNT(*)
FROM `roles` AS `laravel_reserved_0`
INNER JOIN `department_hierarchy`
ON `laravel_reserved_0`.`id` = `department_hierarchy`.`child_id` <-- look at laravel_reserved_0
WHERE `roles`.`id` = `department_hierarchy`.`parent_id`) AS `children_count`
FROM `roles`
When extending \Spatie\Permission\Models\Role:
echo \App\Models\Department::withCount('children')->toSql();
/**
SELECT `roles`.*, (
SELECT COUNT(*)
FROM `roles` AS `laravel_reserved_0`
INNER JOIN `department_hierarchy`
ON `roles`.`id` = `department_hierarchy`.`child_id` <------ laravel_reserved_0 != roles
WHERE `roles`.`id` = `department_hierarchy`.`parent_id`) AS `children_count`
FROM `roles`
withCount() uses Model::table field to temporary store alias name (laravel_reserved_0).
And when (in Illuminate\Database\Eloquent\Model) method Model::getTable() returns $this->table or magic name from class basename, your version returns only pre-configurated table name (config('permission.table_names.roles')) or, if configuration not found, Model::getTable(). So if permission.table_names.roles is configured, it has no change to return $this->table.
I would recommend to rewrite this method like this:
public function getTable()
{
return $this->table ?? config('permission.table_names.roles', parent::getTable());
}
or for best practice remove method Role::getTable() and replace it with
I needed to get ManyToMany relation of roles (structure of departments). To do this, I extended the
\Spatie\Permission\Models\Role
class with methods:and created migration:
Everything works well except methods like
and so on: it always returns
parent_count = 0
.The reason of this behavior is in overriding of method
getTable
inSpatie\Permission\Models\Role
.When extending
Illuminate\Database\Eloquent\Model
:When extending
\Spatie\Permission\Models\Role
:withCount()
usesModel::table
field to temporary store alias name (laravel_reserved_0
).And when (in
Illuminate\Database\Eloquent\Model
) methodModel::getTable()
returns$this->table
or magic name from class basename, your version returns only pre-configurated table name (config('permission.table_names.roles')
) or, if configuration not found,Model::getTable()
. So ifpermission.table_names.roles
is configured, it has no change to return $this->table.I would recommend to rewrite this method like this:
or for best practice remove method Role::getTable() and replace it with
The text was updated successfully, but these errors were encountered: