php - Doctrine ORM 对象类型列未序列化

标签 php symfony doctrine-orm

我正在开发 REST api,并且我有一列类型对象作为我的 User 类的属性。在我的用户实体中,我有:

/**
 * @var stdClass
 * @Serializer\Expose
 * @Serializer\Groups({"list", "details"})
 * @ORM\Column(type="object", name="notifications")
 */
protected $notifications;

创建新用户时,我使用不同通知的默认值初始化此字段,如下所示:

$_notifications = new \stdClass();

$_notifications->voucherSold = true;
$_notifications->voucherRedeemed = true;
$_notifications->newConnection = true;

$user->setNotifications($_notifications);

我可以看到该字段已正确写入数据库。在我的数据库中,在 notifications 列下,我得到:

O:8:"stdClass":3:{s:11:"voucherSold";b:1;s:15:"voucherRedeemed";b:1;s:13:"newConnection";b:1;}

但是当我通过 API 加载此用户时,我最终在通知字段中得到一个空对象:

{
  "resource": "vendors/39",
  "id": 39,
  "email": "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2c6d7c1c6f2c7c1d7c09cd1dddf" rel="noreferrer noopener nofollow">[email protected]</a>",
  "notifications": {},
  "company": "",
  "address": "",
  "city": "",
  "state": "",
  "zipcode": "",
  "phone": "",
  "website": ""
}

我不明白为什么该值没有通过。有任何想法吗?谢谢。

最佳答案

json 编码器只能将数组转换为 json,并且只会将对象设置为对象 {},而不是查找其中的字段等。

在返回之前尝试将 $_notifications 对象转换为数组:

$user->setNotifications((array) $_notifications);

关于php - Doctrine ORM 对象类型列未序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32701403/

相关文章:

php - 如何通过比较格式错误的日期字符串和今天的日期来过滤结果集行?

mysql - Doctrine2 中从 n+1 到 n-1 的订购日期

javascript - Symfony - 渲染表单(带原型(prototype))

doctrine-orm - 学说 2 级联 = {'' 删除"} 似乎不起作用

php - 学说多对多关联 prePersist 数据复制

PHPUnit:死后继续,期望 "die"或以某种方式处理 die()?

php - MySQL 表 : Display every row with criteria met

php - 如何增加 Symfony2 中的 session 生命周期?

php - 通过查询或 php 将来自 MySQL 的消息按主题分组

php - 未创建 Wordpress 图像缩略图