0

Within my database I have two related tables.

AppBooking

AppBookingService

AppBookingService has a foreign key to AppBooking

I use this method to make an insertion in both the first and second 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);
    }
}

The data is written correctly

After that, in the same http request, I invoke the method below in order to have AppBooking Service data within my entity

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

The problem that the AppBooking entity I get does not contain AppBookingService

The method

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

returns 0

If I make the same call in another http request I get the desired result.

It is as if doctrine did not update the entity in that same request

This is a part of AppBooking

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

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

This is part of 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;
ciro
  • 771
  • 1
  • 8
  • 30

1 Answers1

1

This is because when running

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

The entity is fetched from his internal proxy cache. No database query is executed to get the entity `s data. The same is true for its already loaded associations. The Proxy cache is valid during the execution of a http request.

To solve this, you either have to update the $services Collection manually or refresh the entity.

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

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

You can also clear the entire entity manager cache before calling the findOne() method.

$this->em->clear();

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

References

Jannes Botis
  • 11,154
  • 3
  • 21
  • 39