具有连接表的Doctrine查询构建器ManyToMany

时间:2018-04-28 18:49:13

标签: php mysql doctrine-orm

我尝试通过doctrine查询构建器构建类似此查询的内容:

SELECT m.id
FROM product p, model m
  INNER JOIN product_model pm ON (m.id = pm.model_id)
WHERE p.id = pm.product_id AND m.serial = ? AND p.id = ?

表'product_model'是ManyToMany单向关系中的JoinTable。我使用下面的代码:

$queryBuilder = $this->entityManager->createQueryBuilder();
        $queryBuilder
            ->select('m.id')
            ->from(Model::class, 'm')
            ->join(Product::class, 'p', Join::ON, '1 = 1')
            ->where('m.serial.serial = :serial')
            ->andWhere('p.productId.id = :productId')
            ->setParameters(
                [
                    'serial'    => (string)$serial,
                    'productId' => $productId->value(),
                ]
            );
        $query = $queryBuilder->getQuery();
        $results = $query->getOneOrNullResult();

但是当我尝试转储此查询的sql时,我得到了:

SELECT m0_.id AS id_0 FROM model m0_ INNER JOIN product p1_ ON (1 = 1) WHERE m0_.serial = ? AND p1_.id = ?

此查询的结果不是我的预期

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。我需要另一个product_model tabel的实体类,其中包含复合键和查询中的litle更改:

$queryBuilder
            ->select('m.id')
            ->from(Model::class, 'm')
            ->join(ProductModel::class, 'pm', Join::WITH, $queryBuilder->expr()->eq('m.id', 'pm.modelId'))
            ->where('m.serial.serial = :serial')
            ->andWhere('pm.productId = :productId')
            ->setParameters(
                [
                    'serial'    => (string)$serial,
                    'productId' => $productId->value(),
                ]
            );