在ZF2和Doctrine

时间:2015-11-24 16:39:54

标签: php doctrine-orm zend-framework2 many-to-many query-builder

用户信息:

namespace Module\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zend\Stdlib\Hydrator;

/**
 * Info
 *
 * @ORM\Table(name="user_info")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="Module\Entity\InfoRepository")
 */
class Info
{
    /**
     * @var ArrayCollection $champions
     *
     * @ORM\ManyToMany(targetEntity="Module\Entity\Champion", inversedBy="infos")
     */
    private $champions;
}

冠军:

namespace Module\Entity;

use Doctrine\ORM\Mapping as ORM;
use Zend\Stdlib\Hydrator;

/**
 * Champion
 *
 * @ORM\Table(name="champion")
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="Module\Entity\ChampionRepository")
 */
class Champion
{
    /**
     * @var ArrayCollection $infos
     *
     * @ORM\ManyToMany(targetEntity="Module\Entity\Info", mappedBy="champions")
     */
    private $infos;
}

此代码在数据库中工作并创建表info_champion

我想只使用doctrine QueryBuilder选择包含与某个特定冠军的关系的信息,就像这个SQL查询一样:

SELECT i.* FROM `user_info` AS i 
  LEFT JOIN info_champion ic ON ic.info_id = i.id 
  WHERE ic.champion_id = 2;

1 个答案:

答案 0 :(得分:1)

在您的用户信息库中:

$queryBuilder = $this->createQueryBuilder('i')
    ->addSelect('ic') //only needed if you want to fetch join...
    ->innerJoin('i.champions', 'ic')
    ->where('ic.id = :champion_id')
    ->setParameter('champion_id', 2);

$query = $queryBuilder->getQuery();

return $query->getResult();