我希望将我的一个实体对象保存到会话中,但在保存时,我遇到了以下两个错误:
异常: Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::serialize() 必须返回一个字符串或 NULL
和
ErrorException: 注意:serialize():从__sleep()返回的成员变量“id”不存在于 /var/www/clients/client71/web256/web/_dev_fd/kkupon/vendor/symfony/src/Symfony/Component/HttpKernel/DataCollector/DataCollector.php 第 29 行
我的代码如下:
异常: Symfony\Bundle\FrameworkBundle\DataCollector\RequestDataCollector::serialize() 必须返回一个字符串或 NULL
和
ErrorException: 注意:serialize():从__sleep()返回的成员变量“id”不存在于 /var/www/clients/client71/web256/web/_dev_fd/kkupon/vendor/symfony/src/Symfony/Component/HttpKernel/DataCollector/DataCollector.php 第 29 行
我的代码如下:
$offer = $this->getEntityManager()->getRepository('KkuponMainBundle:Offer')->find($offer_id);
$request->getSession()->set('offer', $offer);
我应该如何做才能做对呢?
谢谢。
更新 在Rowgm的帮助下,我通过将属性设置为protected而不是private来解决了这个问题。唯一的问题是,在从会话中读取实体后,EntityManager并不知道它,如果我将对象(从会话中)添加到另一个对象中(它们之间存在OneToMany关系),它将无法正常工作。
<?php
$offer = $this->get('session')->get('offer');
$coupon = new Coupon();
$coupon->setOffer($offer);
$this->em->persist($coupon);
$this->em->flush();
这会引发错误,因为按照EntityManager的说法,coupon具有一个对象属性,而该属性不在数据库中(实际上该属性是从数据库中放入会话中的)。
<?php
$offer = $this->get('session')->get('offer');
echo $this->em->getUnitOfWork()->isInIdentityMap($offer) ? "yes":"no"; //result: no
一种解决方案是:
$offer = $this->em->merge($offer);
但这似乎不是最好的方法。我希望我的EntityManager能够感知存储在会话中的实体对象,而不需要每次都告诉它。
有什么想法吗?