很多人都在查询Buider Symfony2

时间:2015-05-04 11:20:07

标签: symfony orm many-to-many query-builder

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

class Category
{
    ...

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

    ...

}

和产品类

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

如何获得结果?

1 个答案:

答案 0 :(得分:0)

您需要使用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();

如果您需要使用不同的属性进行过滤,我已使用类别的ID进行过滤,然后更改c.id => c.any other property