Dennis
Dennis

Reputation: 3488

Doctrine 2 entities with one to many relations

I'm trying to fetch an annotation with an one to many relation but as soon as I use a join I will end up with the following data:

entities\Topic
    id    = 1            // integer
    title = "example"    // string
    comments             // entities\Comment = oneToMany
        id   = 1                    // integer
        comment = "first comment"   // string
        topic                       // entities\Topic = manyToOne
            id    = 1 // again..
            title = "example"

Why does doctrine fetch the the manyToOne relation inside comments when I join on the topics comments? This is my query:

$this->em->createQueryBuilder()
         ->from('Entities\Topic', 't')
         ->select("t, c")
         ->leftjoin("t.comments", 'c')
         ->where('t.id = :id')
         ->setParameter('id', 1)
         ->getQuery()->getSingleResult();

Shouldn't the topic property be null or at least an empty arrayCollection?

Another thing:

Why do I get a PersistentCollection back as comments when I specify that comments is an arrayCollection? Do I always need to use unwrap on the PersistentCollection before I can loop through it?

Upvotes: 2

Views: 1101

Answers (1)

timdev
timdev

Reputation: 62914

On the first bit - it's likely populating the topic because it already has the data. Were the data not already on-hand, you'd likely have a proxy entity there. It would never be null, because null would be wrong (the comment does have a topic).

As for ArrayCollection/PersistentCollection, you can safely ignore the distinction. I don't know the implementation details, but basically, the EM gives back stuff in PersistentCollections, which I assume play a role in managing the entities in the collection. If you're creating the collection, you use ArrayCollection. Sorry I can't be more specific here, but the bottom line is, you should probably just think about any PersistentCollections you get from the EM as just "a collection"

Upvotes: 3

Related Questions