How to add an item in the Collection of an already hydrated entity

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.

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *