将SQL转换为DQL

时间:2014-07-21 21:16:05

标签: symfony doctrine-orm

我正在尝试使用createQueryBuilder()和innerJoin()将此SQL转换为DQL,但有点困惑。

ORM

class Brands
{
    private $id;
    /**
     * @ORM\OneToMany(targetEntity="Cars", mappedBy="brands")
     */
    private $cars;
}

class Cars
{
    protected $id;
    /**
     * @ORM\ManyToOne(targetEntity="Brands", inversedBy="cars")
     * @ORM\JoinColumn(name="brands_id", referencedColumnName="id", nullable=false)
     */
    protected $brands;
}

SQL

SELECT
cars.id AS CarId,
cars.model AS CarModel,
brands.id AS BrandId,
brands.name AS BrandName
FROM cars
INNER JOIN brands ON brands.id = cars.brands_id
ORDER BY
cars.model ASC
AND
brands.name ASC

REPO

$repo = $this->getEntityManager()->getRepository('CarBrandBundle:Cars');

$query = $repo->createQueryBuilder('c')
              ->innerJoin(.....)

接受的答案here对我来说并不干净。我相信有更好的方法。

1 个答案:

答案 0 :(得分:2)

以下是可能对您有所帮助:

$fields = array('c.id', 'c.model', 'b.id', 'b.name');
$repo = $this->getEntityManager()->getRepository('CarBrandBundle:Cars');

$query = $repo->createQueryBuilder('c')
       ->select($fields)
       ->join('c.brands', 'b')
       ->addOrderBy('c.model', 'ASC')
       ->addOrderBy('b.name', 'ASC')
       ->getQuery();
$result = $query->getResult();