I have two entities: One Account can manage several Customers.
Account
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 customer-data in my Twig template. So 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 perfectly fine but when accessing the customer-data another query gets executed for each customer. That means that I have 101 executed queries when printing 100 customers. That's way too much. How can I combine this in one query so that the customer-data gets returned with the account data?
Adding the customers in select method could do the trick to minimize executed queries.
$customers = $qb->select('acc, customer')
->from('AppBundle:Account', 'acc')
->leftJoin('AppBundle:Customer', 'customer', 'WITH', 'customer MEMBER OF acc.customers')
....
;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With