【发布时间】:2020-10-22 10:51:02
【问题描述】:
有没有办法防止 Doctrine 在获取关系时使用数组集合?目标是禁止实体(域层)中的 ORM 代码(包含),因此层是独立的,我正在使用干净的架构。
我有这门课
class User extends AbstractModel implements UserInterface
{
// some other fields
/**
* @var array|RoleInterface[]
*/
private array $roles = [];
/**
* @return RoleInterface[]
*/
final public function getRoles(): array
{
return (array) $this->roles;
}
public function hasRole(RoleInterface $role): bool
{
return in_array($role, $this->roles);
}
/**
* @param RoleInterface[]
*
* @return self
*/
final public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
final public function addRole(RoleInterface $role): self
{
if (! $this->hasRole($role)) {
$this->setRoles([...$this->roles, $role]);
}
return $this;
}
final public function removeRole(RoleInterface $role): self
{
if ($this->hasRole($role)) {
$this->setRoles(array_filter(
$this->roles,
fn (Role $current) => $current === $role
));
}
return $this;
}
}
并且映射是用 XML 完成的
<doctrine-mapping xmlns="https://doctrine-project.org/schemas/orm/doctrine-mapping"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping
https://raw.github.com/doctrine/doctrine2/master/doctrine-mapping.xsd">
<entity name="App\Domain\Model\User\User">
<!-- some other fields -->
<many-to-many field="roles" target-entity="App\Domain\Model\Role\Role">
<join-table name="user_role">
<join-columns>
<join-column name="user_id" referenced-column-name="id" nullable="false" unique="false" />
</join-columns>
<inverse-join-columns>
<join-column name="role_id" referenced-column-name="id" nullable="false" unique="false" />
</inverse-join-columns>
</join-table>
</many-to-many>
</entity>
</doctrine-mapping>
问题是在获取用户时,Doctrine 尝试将 ArrayCollection 放入用户中,这导致错误 500。 我知道我可以删除输入并只执行 $collection->toArray(),但这意味着我的模型符合 ORM,它应该是相反的。
有没有办法配置 Doctrine 以返回一个本地数组来表示关系? YML、XML 或 PHP 都可以。
【问题讨论】:
标签: symfony doctrine relation arraycollection