Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Doctrine Eager Load in Query

I use Symfony 2.4.2 I have two Doctrine Entities. Entites names: City and Town.

Relationship structure:

City -> Town = OneToMany Town -> City = ManyToOne

Entity/City.php

/**
 * @ORM\OneToMany(targetEntity="Town", mappedBy="city")
 */
private $towns;

Entity/Town.php

/**
 * @ORM\ManyToOne(targetEntity="City", inversedBy="towns")
 * @ORM\JoinColumn(name="city_id", referencedColumnName="id")
 */
private $city;

Where In Query not running in the second and third items.

1-) Town=>City Query(Working) Profiler SS: http://prntscr.com/34lx9q

$query = $this->_entityManager->createQuery('SELECT town FROM PersonalSiteBundle:Town town');
$query->setFetchMode(
    'Personal\SiteBundle\Entity\Town',
    "city",
    \Doctrine\ORM\Mapping\ClassMetadata::FETCH_EAGER
);
$query->execute();

2-) Town=>City Query(Not Working) Profiler SS: http://prntscr.com/34ly4h

$query = $this->_entityManager->createQuery('SELECT town FROM PersonalSiteBundle:Town town');
$query->setFetchMode(
    'Personal\SiteBundle\Entity\Town',
    "city",
    \Doctrine\ORM\Mapping\ClassMetadata::FETCH_EAGER
);
$query->execute(array(),Query::HYDRATE_ARRAY);

3-) City=>Town Query(Not Working) Profiler SS: http://prntscr.com/34ly4h

$query = $this->_entityManager->createQuery('SELECT city FROM PersonalSiteBundle:City city');
$query->setFetchMode(
    'Personal\SiteBundle\Entity\City',
    "towns",
    \Doctrine\ORM\Mapping\ClassMetadata::FETCH_EAGER
);
$query->execute(array(),Query::HYDRATE_ARRAY);
like image 237
mollyjane Avatar asked Mar 27 '14 17:03

mollyjane


Video Answer


1 Answers

If you want to do it in a repository, you can do a JOIN and adding the resource to the selected objects.

This is the QueryBuilder version:

$qb = $this->createQueryBuilder('city')
    ->addSelect('town')
    ->innerJoin('town.city', 'city');
$cities = $qb->getQuery()->getResult();
like image 127
goto Avatar answered Oct 01 '22 01:10

goto