我想为每个用户设置默认角色ROLE USER
,但不想为每个默认用户角色设置关系<->。
这意味着我将通过添加默认角色来扩展Role实体中的方法。
问题是我的Member实体中没有角色数组,而且我看到许多实现该逻辑的示例。相反,我在WorkspaceMember和Role实体之间有***ManyToMany***关系。
角色实体:
<many-to-many field="workspaceMember" target-entity="WorkspaceMember" inversed-by="teamMemberRoles" fetch="LAZY">
<join-table name="team_member_role">
<join-columns>
<join-column name="role_id" referenced-column-name="id"/>
</join-columns>
<inverse-join-columns>
<join-column name="team_member_id" referenced-column-name="id"/>
</inverse-join-columns>
</join-table>
</many-to-many>
在角色类中
private $workspaceMember;
..... more code
$this->workspaceMember = new ArrayCollection();
.....
/**
* @return Collection<int, WorkspaceMember>
*/
public function getWorkspaceMember(): Collection
{
return $this->workspaceMember;
}
public function addWorkspaceMember(WorkspaceMember $workspaceMember): self
{
if (!$this->workspaceMember->contains($workspaceMember)) {
$this->workspaceMember[] = $workspaceMember;
}
return $this;
}
public function removeWorkspaceMember(WorkspaceMember $workspaceMember): self
{
$this->workspaceMember->removeElement($workspaceMember);
return $this;
}
与工作区成员实体
<many-to-one field="member" target-entity="Member" fetch="LAZY" inversed-by="workspaceMembers">
<join-columns>
<join-column name="member_id" referenced-column-name="id"/>
</join-columns>
</many-to-one>
<many-to-many field="teamMemberRoles" target-entity="Role" mapped-by="workspaceMember" fetch="LAZY"/>
在工作区成员类中
private $teamMemberRoles;
.....more code
$this->teamMemberRoles = new ArrayCollection();
.....
/**
* @return Collection<int, Role>
*/
public function getTeamMemberRole(): Collection
{
return $this->teamMemberRoles;
}
public function addTeamMemberRole(Role $teamMemberRole): self
{
if (!$this->teamMemberRoles->contains($teamMemberRole)) {
$this->teamMemberRoles[] = $teamMemberRole;
$teamMemberRole->addWorkspaceMember($this);
}
return $this;
}
public function removeTeamMemberRole(Role $teamMemberRole): self
{
if ($this->teamMemberRoles->removeElement($teamMemberRole)) {
$teamMemberRole->removeWorkspaceMember($this);
}
return $this;
}
有人能帮帮忙吗?
1条答案
按热度按时间2ic8powd1#
与@alexcm的注解类似,我所做的是修改文档中的示例
getRoles
,以返回$roles
元素的副本,并将'ROLE_USER'
插入其中这既满足了安全层的期望,又将
ArrayCollection
从代码的其余部分隐藏起来(IME不鼓励公开DoctrineCollection
对象,尽管我找不到权威的来源来支持这一点。