Convert SQL with subquery to Doctrine Query Builder

好久不见. 提交于 2019-12-11 07:36:37

问题


I have follow database structure:


List item

trips (ManyToMany to tags over table trips_tags)
+----+----------------+
| id |      name      |
+----+----------------+
|  1 | Czech Republic |
|  2 | Germany        |
|  3 | Poland         |
+----+----------------+

tags
+----+-----------+
| id |   name    |
+----+-----------+
|  1 | Mountains |
|  2 | Beach     |
|  3 | City      |
+----+-----------+

trips_tags
+----------+---------+
| trips_id | tags_id |
+----------+---------+
|        1 |       1 |
|        1 |       2 |
|        3 |       1 |
+----------+---------+

I need to select trips which has all tags I specify.

  • Need trips for tags Mountains as Beach I get only Czech Republic.
  • Need trips only for tag Mountains, get Czech Republic and Poland

I wrote a simple SQL

SELECT trip.name, trip.id
FROM trips AS trip
WHERE (
    SELECT COUNT(trip_tag.tags_id) 
    FROM trips_tags AS trip_tag 
    WHERE trip_tag.tags_id IN (1, 2) 
      AND trip_tag.trips_id = trip.id
) = numberOfTags`

Now I have a problem to write this SQL in DQL. Can anyone help?

Thank you


回答1:


It looks like you have many to many relationship between trips and tags, Its better to go with doctrine way and define your entites and relate them as many to many like

class Trip
{
    // ...

    /**
     * @ManyToMany(targetEntity="Tag", inversedBy="trips")
     * @JoinTable(name="trip_tag")
     */
    private $tags;

    public function __construct() {
        $this->tag s= new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

/** @Entity */
class Tag
{
    // ...
    /**
     * @ManyToMany(targetEntity="Trip", mappedBy="tags")
     */
    private $trips;

    public function __construct() {
        $this->trips = new \Doctrine\Common\Collections\ArrayCollection();
    }

    // ...
}

And then build your DQL with some aggregation

$tagIds = [1,2];
$qb = $this->createQueryBuilder('trip');
$qb ->addSelect('COUNT(tags.id) AS total_tags')
    ->leftJoin('trip.tags', 'tags')
    ->add('where', $qb->expr()->in('tags', $tagIds))
    ->groupBy('trip.id')
    ->having('total_tags = @numberOfTags')
    ->getQuery()
    ->getResult();

Many-To-Many, Bidirectional

Doctrine2 get object without relations

Symfony2 - Doctrine2 QueryBuilder WHERE IN ManyToMany field



来源:https://stackoverflow.com/questions/50682967/convert-sql-with-subquery-to-doctrine-query-builder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!