原则多对多 - 产品和类别

doctrine many to many - product and category

如何构建搜索查询以使用类别搜索产品?以下是我的分类和产品。

这是我的产品实体

class Product {
    /**
     * @ORM\Id
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

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


    /**
     * @var \Doctrine\Common\Collections\Collection|UserGroup[]
     *
     * @ORM\ManyToMany(targetEntity="Catalog\Model\Entity\Category", inversedBy="product")
     * @ORM\JoinTable(
     *  name="product_category",
     *  joinColumns={
     * @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     *  },
     *  inverseJoinColumns={
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
     *  }
     * )
     */
    protected $categories;

}

并且这是类别实体..

class Category {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;
    /**
     * @ORM\Column(type="string", length=255, nullable=false)
     */
    protected $title;

    /**
     * @ORM\ManyToOne(targetEntity="Catalog\Model\Entity\Product", inversedBy="categories")
     */
    /**
     * @var \Doctrine\Common\Collections\Collection|Product[]
     *
     * @ORM\ManyToMany(targetEntity="Catalog\Model\Entity\Product", mappedBy="categories")
     */
    protected $products;
} 

我正在尝试构建搜索查询。我应该如何修改以下查询以使用类别进行搜索?

    $productName = $searchParams['productName'];

    $arrWhere = array();
    $productSql = "SELECT p FROM \Catalog\Model\Entity\Product p";

    if ($productName) {
        array_push($arrWhere, "p.name LIKE '" . '%'.$productName.'%' . "'");
    }


    if (count($arrWhere) > 0) {
        $productSql.= " WHERE " . implode(' AND ',$arrWhere);
    }

    $productSql.= $order_query_str;

    $query = $em->createQuery($productSql);

我建议使用 Doctrine 的查询生成器。

$qb = $em->createQueryBuilder();
$qb->select(‘p’)
    -> from('\Catalog\Model\Entity\Product')
    ->leftJoin('p.categories', 'c');


if (isset($searchParams['productName'])) {
    $qb->andWhere('p.name LIKE :prodName')
        ->setParameter('prodName', '%' . $searchParams['productName'] . '%');
}
if (isset($searchParams['categoryTitle'])) {
    $qb->andWhere('c.title LIKE :catTitle')
        ->setParameter('catTitle', '%' . $searchParams['categoryTitle'] . '%');
}

$query = $qb->getQuery();