I am trying to port my PHP application to Zend Framework with Doctrine2. It's a webshop platform. I need to write a DQL query with a extra condition to select accessoires from products who are in user's shoppingcart.
I have a traditional query:
SELECT
...
FROM
product
INNER JOIN
accessory_to_product ON(product.productid = accessory_to_product.accessoryid AND accessory_to_product.productid IN(000,000,000))
But this has to be Doctrine. I have the following entity:
<?php
/**
* @ORM\Table(name="product")
* @ORM\Entity(repositoryClass="BestBuy\Entity\Repository\ProductRepository")
*/
class Product extends \BasicEntity
{
/**
*
* @var integer
* @ORM\Column(type="integer",nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $productid;
/**
*
* @var string
* @ORM\Column(type="string",nullable=false)
*/
protected $title;
/**
*
* @var string
* @ORM\Column(type="text",nullable=false)
*/
protected $description;
/**
*
* @var string
* @ORM\Column(type="datetime",nullable=false)
*/
protected $insertdate;
//....
/**
*
* @var array
*
* @ORM\ManyToMany(targetEntity="Product")
* @ORM\JoinTable(name="accessory_to_product",
* joinColumns={@ORM\JoinColumn(name="accessoryid", referencedColumnName="productid")},
* inverseJoinColumns={@ORM\JoinColumn(name="accessoryid", referencedColumnName="productid", unique=false)});
*/
protected $accessories;
}
Thus I want to rewrite this query to Doctrine2:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('p')
->from('BestBuy\Entity\Product', 'p')
->join('p.accessories', 'a', Expr\Join::WITH, $qb->expr()->in('p.productid', ':products'))
->setParameter('products', $products);
But this gives me the following query:
SELECT
p0_.productid AS productid0,
p0_.title AS title1,
p0_.description AS description2,
p0_.insertdate AS insertdate3,
p0_.price AS price4,
p0_.model AS model5,
p0_.categoryid AS categoryid6,
p0_.deliverytimeid AS deliverytimeid7,
p0_.status AS status8,
p0_.weight AS weight9,
p0_.pagetitle AS pagetitle10,
p0_.metadescription AS metadescription11,
p0_.youtubecode AS youtubecode12
FROM
product p0_
INNER JOIN
accessory_to_product a2_ ON p0_.productid = a2_.accessoryid
INNER JOIN
product p1_ ON p1_.productid = a2_.accessoryid AND (p0_.productid IN (11224))
This is almost correct except that the accessory_to_product table is joined twice. Does anyone has a tip for me? Actually I should select FROM accessoires and then join to product, but since this is a relation to product this isn't possible.