学说 2 实体未填充子元素

doctrine 2 entity is not filled with childs element

在我的数据库中,我有两个相关的 tables。

AppBooking

AppBookingService

AppBookingService 有 AppBooking 的外键

我用这个方法在第一个和第二个都插入了table。

public function bookingExecute($data){
    try{
        $this->em->beginTransaction();
        $appBooking = $this->_fillAppBooking($data);
        $this->em->persist($appBooking);
        if(array_key_exists("appService",$data) && is_array($data['appService']) && count($data['appService']) > 0){
            foreach($data['appService'] as  $bookingService){
                $appBookingService = $this->_fillAppBookingService($bookingService,$appBooking);
                $this->em->persist($appBookingService);
                $this->em->flush();
            }
        }
        $this->em->flush();
        $this->em->commit();
        return $appBooking;
    }catch (\Exception $ex){
        $this->em->rollback();
        throw new BookingException("",BookingError::BOOKING_QUERY_ERROR);
    }
}

数据写入正确

之后,在同一个 http 请求中,我调用了下面的方法,以便在我的实体中获得 AppBooking 服务数据

$appBooking = $this->bookingService->findOne($id);

我获取的AppBooking实体不包含AppBookingService的问题

方法

$appBooking->getServices()->count()

returns 0

如果我在另一个 http 请求中进行相同的调用,我会得到想要的结果。

就好像学说没有更新同一请求中的实体

这是 AppBooking 的一部分

/**
 * @var Collection
 * @ORM\OneToMany(targetEntity="AppBookingService", mappedBy="idBooking")
 */
private $services;

public function __construct() {
    $this->services = new ArrayCollection();
}

这是 AppBookingService 的一部分

/**
 * @var \Entity\Entity\AppBooking
 *
 * @ORM\ManyToOne(targetEntity="Entity\Entity\AppBooking", inversedBy="services")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="ID_BOOKING", referencedColumnName="ID_BOOKING", nullable=true)
 * })
 */
private $idBooking;

这是因为当运行

$appBooking = $this->bookingService->findOne($id);

实体是从他的内部代理缓存中获取的。没有执行数据库查询来获取实体的数据。它已经加载的关联也是如此。 代理缓存在http请求执行期间有效。

要解决此问题,您必须手动更新 $services 集合或 refresh 实体。

$this->em->refresh($appBooking);

Refreshes the persistent state of an entity from the database, overriding any local changes that have not yet been persisted.

您还可以clear整个实体管理器缓存调用findOne()方法之前。

$this->em->clear();

Clears the EntityManager. All entities that are currently managed by this EntityManager become detached.

参考资料

  • How do I force doctrine to reload the data from the database?