1

I'm trying to turn this SQL into DQL with createQueryBuilder() and innerJoin() but confused a bit.

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(.....)

Accepted answer here didn't look clean to me. I believe there is better way of doing it.

Community
  • 1
  • 1
BentCoder
  • 12,257
  • 22
  • 93
  • 165

1 Answers1

2

Here is what may help you:

$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();
Javad
  • 4,339
  • 3
  • 21
  • 36