多对多查询构建器 Symfony2

Many to Many Query Buider Symfony2

我有两个实体。类别和产品。他们映射了 ManyToMany。

class Category
{
    ...

   /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    ...

}

和产品class

class Product
{
    ...

   /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255)
     */
    private $name;

    /**
     *
     * @ORM\ManyToMany(targetEntity="App\MyBundle\Entity\Category", inversedBy="name")
     * @ORM\JoinColumn(name="category", referencedColumnName="id", nullable=true)
     */
    private $category;
}


    $repository = $this->getDoctrine()->getRepository('AppMyBundle:Product');
    $product = $repository->createQueryBuilder('product')
             ->where('product.category = ?1')->setParameter(1, $variable)
             ->getQuery()->getResult()

如何得到结果?

您需要 join() 方法将产品与类别实体结合起来,然后在 where() 部分添加您的过滤条件

$repository = $this->getDoctrine()->getRepository('AppMyBundle:Product');
$product = $repository->createQueryBuilder('product')
    ->join('product.category','c')          
    ->where('c.id = ?1')
    ->setParameter(1, $variable)
    ->getQuery()->getResult();

如果你需要用不同的过滤属性然后更改c.id=>c.any other property

,我已经使用类别id进行过滤