【问题标题】:Convert SQL with subquery to Doctrine Query Builder将带有子查询的 SQL 转换为 Doctrine Query Builder
【发布时间】:2018-06-04 14:32:43
【问题描述】:

我有以下数据库结构:

项目清单 trips(ManyToMany 到表 trips_tags 上的标签) +----+----------------+ |编号 |姓名 | +----+----------------+ | 1 |捷克共和国 | | 2 |德国 | | 3 |波兰 | +----+----------------+ 标签 +----+------------+ |编号 |姓名 | +----+------------+ | 1 |山脉 | | 2 |海滩 | | 3 |城市 | +----+------------+ trips_tags +---------+---------+ | trips_id |标签_id | +---------+---------+ | 1 | 1 | | 1 | 2 | | 3 | 1 | +---------+---------+

我需要选择包含我指定的所有标签的行程。

  • 需要将 Mountains 标记为 Beach 我只得到捷克共和国。
  • 只需要标签山脉的旅行,获得捷克共和国和波兰

我写了一个简单的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`

现在我在用 DQL 编写此 SQL 时遇到问题。有人可以帮忙吗?

谢谢

【问题讨论】:

  • 你在什么框架下工作?通常,如果您使用 Doctrine,您会创建实体类,然后使用 Doctrine PHP 注释并在这些类中建立关系。你永远不应该写这样的裸查询。一切都应该在 Doctrine 本身中处理。
  • 我在 Nette FW 工作。我对实体的设计没有问题,但我不知道如何在 DQL 中创建查询 :)
  • 很公平,我不清楚你是否得到了那部分。

标签: php doctrine-orm query-builder


【解决方案1】:

看起来你在旅行和标签之间有多对多的关系,最好用学说的方式定义你的实体并将它们像多对多的关系一样

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();
    }

    // ...
}

然后用一些聚合构建你的 DQL

$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

【讨论】:

  • 是的,它看起来不错并且可以使用,但是我需要获取 Trips 实体的数组?现在我只得到 total_tags 值的数组。有可能吗?
  • @iwory 您可以在查询中添加->select('trip') 以获取行程集合
  • 是的,我们正在接近 :) 现在我得到数组,其中每个项目都有两个键 -> Trip 实体和 total_tags 值。可以删除 total_tags 键并仅获得明确的 Trips 数组吗?非常感谢
  • @iwory 我想您需要手动转换它,对此不确定。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-10
  • 2021-02-04
  • 1970-01-01
  • 2023-03-20
  • 2015-05-12
  • 2014-07-12
相关资源
最近更新 更多