首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Symfony -向集合中添加硬编码值

Symfony -向集合中添加硬编码值
EN

Stack Overflow用户
提问于 2022-07-07 03:51:34
回答 1查看 56关注 0票数 0

我的WorkspaceUser表和Role表之间有如下的Role关系:

代码语言:javascript
复制
<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>

代码语言:javascript
复制
<entity name="WorkspaceUser" table="role">
    ... 
    <many-to-many field="workspaceUserRoles" target-entity="Role" mapped-by="workspaceUser" fetch="LAZY"/>

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

Byt,我如何硬编码USER_ROLE,使它可以在默认情况下与每个用户一起返回?

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

代码语言:javascript
复制
/**
 * @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;
}
EN

回答 1

Stack Overflow用户

发布于 2022-07-07 20:55:55

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

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

代码语言:javascript
复制
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;
}

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72892088

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档