0

In Sylius, translatable entities use an ArrayCollection to handle translations, for example Product entity has ProductTranslation entities in translations attribute.

Given an already hydrated entity $object from the database we have one item in $object->translations.

Now, I want to add another existing translation into my $object from the database.

        $qb = $this->createQueryBuilder('o');
        $qb
            ->addSelect('fallback_translation')
            ->innerJoin(
                'o.translations',
                'fallback_translation',
                'WITH',
                'fallback_translation.locale = :fallback_translation'
            )
            ->setParameter('fallback_translation', $locale)
            ->where('o = :translatable')
            ->setParameter('translatable', $object)
        ;

        /** @var TranslatableInterface $translation */
        $translation = $qb->getQuery()->getSingleResult();

        dump($object === $translation); // true

With this code, the $translation entity is the same as $object (same object reference) without the new locale in the collection and I don't understand why. I think it's related to the hydration with Doctrine, but I'm not aware of the logic behind.

My query is OK because if I force the mode AbstractQuery::HYDRATE_ARRAY, my array contains the right data. My need is really to have an hydrated object, so updating the existing entity by adding the new translation to the collection of $object would be perfect.

DjLeChuck
  • 308
  • 5
  • 17
  • 1
    Likely this is one of the issues, either the object is part of your UnitOfWork and Doctrine will avoid refetching it. Try doing an `$em->clear()` or use a new entity manager instance before fetching the data to mitigate this. The other possibility, that I can think of, could be a result cache being used try adding `disableResultCache()` to your query. – dbrumann Dec 29 '20 at 17:02
  • @dbrumann you were right, the `$em->clear()` solved the problem! Leave an answer and I will accept it, thank you! – DjLeChuck Dec 30 '20 at 07:40

0 Answers0