我使用nested set在Symfony2中使用StofDoctrineExtension行为。
类别和帖子模型配置得很好,类别树工作正常。
要显示某个类别的帖子,我将从我的存储库中使用此查询:
public function findAllPosts($category)
{
return $this->queryAllPosts($category)->getResult();
}
public function queryAllPosts($category)
{
$em = $this->getEntityManager();
$query = $em->createQuery('
SELECT p, c FROM AppBundle:Post p JOIN p.category c
WHERE c.slug = :category
ORDER BY p.created DESC
');
$query->setParameter('category', $category);
return $query;
}
但是我怎样才能显示这些类别的孩子的帖子呢?
答案 0 :(得分:2)
你应该能够在一个接近这一个的查询中做到这一点,因为我不是专业SQL,它通常需要我时间和测试才能做到正确但这是我要开始的地方:
SELECT parent.* , children.* FROM
(SELECT p, c FROM AppBundle:Post p JOIN p.category c WHERE c.slug = :category) AS parent
INNER JOIN
(SELECT p1 FROM AppBundle:Post p1 JOIN p.category c1 ON c1.parent = parent.id ) AS children
不确定是否需要在内部选择内部执行ON或者为连接选择包装器,但您可以尝试:)
答案 1 :(得分:1)
如果CategoryRepository
继承自NestedTreeRepository
,您可以执行以下操作:
$categories = $em->getRepository('XBundle:Category')
->childrenQueryBuilder($category)
->addSelect('posts')
->join('node.posts', 'posts')
->getQuery()
->getResult();
foreach ($categories as $category) {
$category->getPosts();
// do stuff
}
答案 2 :(得分:0)
我找到了方法。查询将是这样的:
/*
* GET POSTS FROM PARENT AND CHILDREN
*/
public function getPostsParentAndChildren($children)
{
$em = $this->getEntityManager();
$posts = $em->createQueryBuilder()
->select(array('p', 'c'))
->from('AppBundle:Post', 'p')
->join('p.category', 'c')
->where('c.id IN (:children)')
->orderBy('p.created', 'DESC')
->getQuery();
$posts->setParameter('children', $children);
return $posts->getResult();
}
我们将带有子节点的数组传递给查询,我们使用函数getChildren($ categoryId)获取该数组。请记住,您必须传递id(使用此查询),因此您可以获得这样的ID:
$category = $repo->findOneBy(array('slug' => $slug1));
$children = $repo->getChildren($category);
$childrenIds[] = $category->getId();
foreach ($children as $child){
$id = $child->getId();
$childrenIds[] = $id;
}
$posts = $em->getRepository('AppBundle:Category')->getPostsParentAndChildren($childrenIds);