doctor查询生成器manytomy与连接表

14ifxucb  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(302)

我尝试通过条令查询生成器构建类似这样的查询:

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 = ?

表“产品模型”是多个单向关系中的一个连接表。我使用以下代码:

$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 = ?

这个查询的结果并不是我所期望的

t2a7ltrp

t2a7ltrp1#

我找到了解决办法。我需要另一个实体类用于product\u model tabel,查询中有复合键和小更改:

$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(),
                ]
            );

相关问题