我创建了自引用的类别实体,产品实体与类别实体的多到多关系。
示例类别列表:
MacBooks
-MacBook Air
--MacBook Air 11
--MacBook Air 13
-MacBook Pro
--MacBook Pro 13我得到的产品是根据选定的类别。
public function getByCategory($category)
{
$qb = $this->createQueryBuilder('p');
$qb->leftJoin('p.categories', 'c');
$qb->where('c.url = :category');
$qb->setParameter('category', $category);
return $qb->getQuery()->useQueryCache(true);
}例如,产品在MacBook Air 13类别内。
因此,我的代码只有在选择类别MacBook Air 13时才能工作。
但是如何在父类中展示产品呢?例如,在MacBook Air类别中,我想显示来自MacBook Air 11 和 MacBook Air 13等类别的产品。
在MacBooks系列中也显示了从MacBook Air,MacBook Air 11,MacBook Air 13等所有的东西.?
问题简化:如何从所有的孩子那里获得所有的产品。
MacBook -> MacBook -> MacBook Air 11,MacBook Air 13
发布于 2017-11-24 18:38:40
你可以试试一件事。首先获取给定类别的所有子级和父级,然后在查询生成器中使用where...in。我们可以通过递归调用来完成它。
YourController.php:
public function someAction(int $id)
{
// ...
$category = $em->getRepository('YourBundle:Category')->find($id);
$categories = $this->getAllCategories($category);
// OR
// $categories = $this->getAllChildren($category);
$products = $em->getRepository('YourBundle:Product')->getByCategories($categories);
// ...
}
private function getAllCategories(Category $category)
{
return array_merge(
$this->getAllChildren($category),
$this->getAllParents($category)
);
}
private function getAllChildren(Category $category)
{
static $categories = array();
$categories[] = $category->getId();
if(!$category->getChildren()->isEmpty())
{
foreach($category->getChildren() as $child)
{
$this->getAllChildren($child);
}
}
return $categories;
}
private function getAllParents(Category $category)
{
static $categories = array();
if($category->getParent())
{
$categories[] = $category->getParent()->getId();
$this->getAllParents($category->getParent());
}
return $categories;
}ProductRepository.php:
// ...
public function getByCategories(array $categories)
{
$qb = $this ->createQueryBuilder('p')
->leftJoin('p.categories', 'c');
$qb->where($qb->expr()->in('c.id', $categories));
return $qb->getQuery()->getResult();
}
// ...所以我们可以得到所有的产品从类别,所有的孩子和父母,或只是从类别和所有的孩子。
希望能帮上忙。
https://stackoverflow.com/questions/47467591
复制相似问题