3

Association mapping in Doctrine 2

<?php
class User
{
    //...
    /**
     * @ManyToMany(targetEntity="Group")
     * @JoinTable(name="User_Group",
     *      joinColumns={@JoinColumn(name="User_id", referencedColumnName="id")},
     *      inverseJoinColumns={@JoinColumn(name="Group_id", referencedColumnName="id")}
     *      )
     */
    private $groups;
    //...
}

In test, assuming in this example $groups initialized as ArrayCollection() in constructor, returns all groups associated with the user.

A programmer in my dev team brought up a good point about this scenario. It loads all groups associated with a user entity, we may not need all of them.

When doing DQL join statements, lets say we want to select the favorite groups, achievable by DQL joins, we join user, group, and favorites. Does Doctrine queries all the groups again? This is the overhead I'm trying to point out, there's already an array collection of all the groups.

How do we control the result from association mapping? Or if we remove association mappings, can we still use DQL to join entities that don't have association mappings setup? OR, does Doctrine actually use the data from the association mapping in DQL?

2
  • Can you please provide more details about your scenario? But in short every time when you do DQL with joins D2 will query all groups again because there is no way for it to know what info will be returned by DQL. If you query by id it will be checking identity map first and return records from it if there is a hit. When you ask $user->getGroups() it will load the whole collection, you might want to check docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/…, it contains some ways to reduce load.
    – WizardZ
    Aug 7, 2012 at 7:01
  • @WizardZ my scenario is already descriptive enough, and the solution to this problem I found after research is to just use DQL partial results.
    – shiva8
    Aug 8, 2012 at 21:05

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.