Symfony2“反向”内连接

时间:2016-10-24 13:39:26

标签: php symfony doctrine-orm

我有2个型号:

class Category
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=63)
     */
    private $name;


class CategoryToAgency
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Agency
     *
     * @ORM\ManyToOne(targetEntity="Agency")
     * @ORM\JoinColumn(name="agency_id", referencedColumnName="id")
     */
    private $agency;

    /**
     * @var Category
     *
     * @ORM\ManyToOne(targetEntity="Category")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     */
    private $category;

我会将一个函数写入CategoryRepository,如:

class CategoryRepository extends EntityRepository
{
    /**
     * @param Agency $agency
     * @return Category[]
     */
    public function findByAgency(Agency $agency)
    {
        $query =  $this->createQueryBuilder('c')
            ->select('Api1Bundle:Category')
            ->from('Api1Bundle:CategoryToAgency', 'ca')
            ->innerJoin('ca.category', 'c')
            ->andWhere('ca.agency = :agency')
            ->setParameter('agency', $agency)
            ->getQuery();

        return $query->getResult();
    }

如何使用此“语法”编写正确的查询?

临时我使用显式查询,但它是这种风格的第一种方法:

    public function findByAgency(Agency $agency)
    {
        $query = $this
            ->getEntityManager()
            ->createQuery('
SELECT c
FROM Api1Bundle:Category AS c
INNER JOIN Api1Bundle:CategoryToAgency AS ca
WITH ca.category = c.id
WHERE ca.agency = :agency
')
            ->setParameter('agency', $agency);

        return $query->getResult();
    }

由于

0 个答案:

没有答案