我的WorkspaceUser表和Role表之间有如下的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之外,所有角色都将来自数据库,而不是硬编码。
Byt,我如何硬编码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;
}发布于 2022-07-07 20:55:55
如果在两个实体之间存在关系,使用外键约束,则不能添加该类型的实体。
但是,在获得这样的角色时,可以动态地添加该角色。
use Doctrine\Common\Collections\ArrayCollection;
// ...
/**
* @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;
}还有其他方法可以做到这一点,这可能不是最优雅的方法,但它是有效的。
https://stackoverflow.com/questions/72892088
复制相似问题