Symfony -在ManyToMany中设置默认角色

kpbwa7wx  于 2022-11-16  发布在  其他
关注(0)|答案(1)|浏览(168)

我想为每个用户设置默认角色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;
}

有人能帮帮忙吗?

2ic8powd

2ic8powd1#

与@alexcm的注解类似,我所做的是修改文档中的示例getRoles,以返回$roles元素的副本,并将'ROLE_USER'插入其中

public function getTeamMemberRole(): array
{
    $roles = this->teamMemberRoles->toArray();
    $roles[] = 'ROLE_USER';
    return array_unique($roles);
}

这既满足了安全层的期望,又将ArrayCollection从代码的其余部分隐藏起来(IME不鼓励公开Doctrine Collection对象,尽管我找不到权威的来源来支持这一点。

相关问题