Search code examples
phpdoctrine-orm

Doctrine query builder ManyToMany with join table


I try to build something like this query by doctrine query builder:

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

Table product_model is a JoinTable in `ManyToMany Unidirectional relationship. I use code below:

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

But when I try to dump SQL of this query I got:

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

And result of this query Isn't what I expected


Solution

  • I found solution. I need another entity class for product_model tabel with composite key and litle changes in query:

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