Symfony-为系列添加硬编码值



我的WorkspaceUser表和Role表之间有很多关系,比如:

<entity name="Role" table="role">
... 
<many-to-many field="workspaceUser" target-entity="WorkspaceUser" inversed-by="workspaceMemberRoles" fetch="LAZY">
<join-table name="workspace_user_role">
<join-columns>
<join-column name="role_id" referenced-column-name="id"/>
</join-columns>
<inverse-join-columns>
<join-column name="workspace_user_id" referenced-column-name="id"/>
</inverse-join-columns>
</join-table>
</many-to-many>

<entity name="WorkspaceUser" table="role">
... 
<many-to-many field="workspaceUserRoles" target-entity="Role" mapped-by="workspaceUser" fetch="LAZY"/>

我的目标是,除了基本的USER_ROLE之外,所有角色都将来自数据库,而不是硬编码。

顺便说一下,我如何对USER_ROLE进行硬编码,以便默认情况下每个用户都可以返回它?

我认为在Collection中添加它是一种方法吗?有人能帮忙吗?

/**
* @return Collection<int, Role>
*/
public function getWorkspaceUserRole(): Collection
{
return $this->workspaceUserRoles;
}
public function addWorkspaceUserRole(Role $workspaceUserRole): self
{
if (!$this->workspaceUserRoles->contains($workspaceUserRole)) {
$this->workspaceUserRoles[] = $workspaceUserRole;
$workspaceUserRole->addWorkspaceUser($this);
}
return $this;
}

如果您在两个实体之间有关系,则使用外键约束不能添加该类型的实体。

但是,您可以在获得这样的角色时动态添加该角色。

use DoctrineCommonCollectionsArrayCollection;
// ...
/**
* @return Collection<int, Role>
*/
public function getWorkspaceUserRoleForSecurity(): Collection
{
// Make a clone of the roles, otherwise the extra role may be stored in the database
$roles = new ArrayCollection($this->workspaceUserRoles->toArray());
$userRole = new Role("USER_ROLE");
if (!$roles->contains($userRole)) {
$roles->add($userRole);
}
return $roles;
}

还有其他方法可以做到这一点,这可能不是最优雅的方法,但它很有效。

最新更新