Symfony2 - OneToMany Select-Issue Doctrine

I have two objects: one account can manage multiple clients.

Score

class Account {
    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\Account", mappedBy="account", cascade={"persist"})
     */
    protected $customers;
}

      

Customer

class Customer {
    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Account", inversedBy="customers", cascade={"persist"})
     * @ORM\JoinColumn(name="accountid", referencedColumnName="id", nullable=true)
     */
    protected $account;

    # + other ManyToMany-Relations
}

      

Now I would like to select all accounts and print the customer details in my Twig template. Therefore, I use the following query:

$qb = $this->getEntityManager()->createQueryBuilder();
$customers = $qb->select('acc')
    ->from('AppBundle:Account', 'acc')
    ->leftJoin('AppBundle:Customer', 'customer', 'WITH', 'customer MEMBER OF acc.customers')
    ->where('customer.active = true')
    ->orderBy('acc.id', 'ASC')
    ->getQuery()
    ->getResult();

      

This works fine, but when accessing client data, a different request is made for each client. This means I have 101 completed requests when printing 100 clients. It's too much. How can I combine this in a single request so that customer data is returned with account data?

+3


source to share


2 answers


Adding clients to the select method can do the trick for minimizing executed queries.



$customers = $qb->select('acc, customer')
    ->from('AppBundle:Account', 'acc')
    ->leftJoin('AppBundle:Customer', 'customer', 'WITH', 'customer MEMBER OF acc.customers')
    ....
;

      

+1


source


So this is a feature of Doctrine2. All relationships are lazy loads if you want to access it.



As a solution, you can change the fetch mode before executing the query.

0


source







All Articles