【问题标题】:doctrine many to many - product and category学说多对多 - 产品和类别
【发布时间】:2016-01-26 05:22:22
【问题描述】:

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

这是我的产品实体

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

【问题讨论】:

    标签: php zend-framework doctrine-orm


    【解决方案1】:

    我建议使用 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();
    

    【讨论】:

      猜你喜欢
      • 2013-07-28
      • 2017-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多