简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM