gpt4 book ai didi

php - PostgreSQL 中的 Doctrine ORM ArrayCollection

转载 作者:可可西里 更新时间:2023-10-31 23:45:53 27 4
gpt4 key购买 nike

我注意到在 PostgreSQL 数据库中使用 Doctrine ORM 的 ArrayCollection 有一些奇怪的事情(在 Symfony 3 项目中使用它)。

将我的 User 类作为角色,它以默认角色 ROLE_USER 启动,并且必须是 array 类型。

class User implements UserInterface, Serializable
{
/**
* @var ArrayCollection
*
* @ORM\Column(name="roles", type="array")
*/
private $roles;

public function __construct()
{
$this->roles = new ArrayCollection();
$this->roles->add('ROLE_USER');
}
}

这存储在数据库中如下。

O:43:"Doctrine\Common\Collections\ArrayCollection":1:{s:53:"

尝试以 User 身份登录时会出现 Serialization 错误,因为数据库中显然缺少 ArrayCollection 的一部分。

在谷歌搜索解决方案后,我遇到了 this Github issue .据我了解,这是一个错误,您不能在 PostgreSQL 环境中使用 ArrayCollection

不在 @ORM\Column 标签中定义类型也无济于事,它随后将以下内容存储在数据库中并且 Symfony 无法使用它检索角色。 学说\Common\Collections\ArrayCollection@000000002300d10300000000545301a6使用 simple_arrayjson 作为类型不会返回对象,所以两者都是不行的

有人对此有解决方法或解决方案吗?我真的开始后悔从 MySQL 切换到 PostgreSQL

注意:代码在 MySQL 中运行良好,我只是切换了数据库。

最佳答案

您始终可以专门为 ArrayCollection 属性创建自己的映射类型。学说 DBAL docsORM cookbook描述如何创建一个。 Symfony documentation描述了如何激活/注册它。

例如,您可以在转换为数据库值时提取数组并对其进行 json 编码:

json_encode($value->toArray())

然后在转换为 PHP 值时进行 json 解码并将其包装回 ArrayCollection:

new ArrayCollection(json_decode($value))

但这是你的映射类型,你可以做任何你想做的:)

关于php - PostgreSQL 中的 Doctrine ORM ArrayCollection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37616407/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com