B
B
BatteryLow2014-02-17 12:38:05
MySQL
BatteryLow, 2014-02-17 12:38:05

Symfony 2 docnrine and fetch related entities?

I just encountered Symfony 2, so there was a slight difficulty due to ignorance of all the subtleties, the actual question is:
There are 3 entities Login, Campain, Banner, they are respectively interconnected Login has an ArrayCollection with associated Campain, it in turn has a collection with its Banner

/**
* @ORM\OneToMany(targetEntity="Campain", mappedBy="Login", indexBy="CampaignID", cascade={"persist", "remove" })
*/
protected $Campains;

/**
 * @ORM\OneToMany(targetEntity="Banner", mappedBy="Campain", indexBy="BannerID", cascade={"persist", "remove" })
*/
protected $Banners;

Is it possible to create a query to create a Login object with all the associated Campains already loaded and for each of them the associated Banners are also selected for 1 time without lazy loading?
I tried this design in the repository, it does not work
$this->getEntityManager()->createQuery('
SELECT Login, Campain, Banner
 FROM BroAppBundle:Login Login
 LEFT JOIN Login.Campains Campain
 LEFT JOIN Campain.Banners Banner
 WHERE Login.User=:user_id')
->setParameter('user_id', $user_id)->getResult();

Tables are attached, but entities are not grouped, and when I call for example a loop
foreach($Logins as $Login){
  foreach($Login->getCampains() as $Campain){
    $Campain->GetBanners();
  }
}

each iteration there are queries to the database for selections.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2014-02-17
Protko @Fesor

you can specify the EAGER selection method in the relationship description, in which your related entities will always be selected via outer join, although it is better to specify this where necessary, and precisely for the query.

$this->getEntityManager()->createQuery('
SELECT l FROM BroAppBundle:Login l
WHERE  Login.User=:user_id')
->setParameter('user_id', $user_id)
->setFetchMode("BroAppBundle:Login", "Campains", "EAGER")
->setFetchMode("BroAppBundle:Login", "Banners", "EAGER")
->getResult();

ps the code may not work, because I don’t remember exactly how it is. Read the docs and try.

A
agladkov, 2014-02-23
@agladkov

www.uvd.co.uk/blog/some-doctrine-2-best-practices

$data = $em->createQueryBuilder()
    ->select(array('l', 'c', 'b'))
    ->from('BroAppBundle:Login', 'l')
    ->leftJoin('l.Campains', 'c')
    ->leftJoin('c.Banners', 'b')
    ->getQuery()
    ->getResult();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question