问题
I have a problem with dql. I can't write properly query. Need to rewrite the query to dql
'SELECT Movie.title, Movie.price, Order.order_data, Order.order_status FROM (Order LEFT JOIN Order_has_Movie ON Order.order_id = Order_has_Movie.order_id) INNER JOIN Movie ON Order_has_Movie.movie_id = Movie.movie_id ORDER BY title DESC'
At the beginning, I wrote something like this:
'SELECT
m.title, m.price, o.order_data, o.order_status
FROM
And I don't know how to deal with this. Could someone tell me, how to wrtie JOINS like this ?
回答1:
You have a many-to-many association between order and movie you can set your entities to achieve this relation something like below
Order Entity
/**
* @ORM\ManyToMany(targetEntity="Namespace\YourBundle\Entity\Movie", cascade={"persist"})
* @ORM\JoinTable(name="Order_has_Movie",
* joinColumns={@ORM\JoinColumn(name="order_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="movie_id", referencedColumnName="id")}
* )
*/
private $movies;
Movie Entity
/**
*
* @ORM\ManyToMany(targetEntity="Namespace\YourBundle\Entity\Order", mappedBy="movies")
*/
private $order;
Now in query builder you can join your order entity with movie like below
$this->createQueryBuilder('o')
->select('o,m')
->innerJoin('o.movies','m')
->orderBy('m.title','DESC')
->getQuery()
->getResult();
Above query will orders and its related movies
For further clarification see docs 22.2.19. @ManyToMany
来源:https://stackoverflow.com/questions/28616655/doctrine-query-language-two-joins-query