使用 Doctrine Extensions Tree Nested set 在 parents 中获取 children 的帖子

Get children's posts in parents with Doctrine Extensions Tree Nested set

我正在使用 nested set behaviour in Symfony2 with StofDoctrineExtension

类别和post模型配置良好,类别树工作正常。

为了显示某个类别的 post,我使用了我存储库中的这个查询:

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

但是我怎样才能同时显示类别 children 的 post?

如果您的 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
}

你应该可以在一个查询中完成这个,因为我不是专业人士 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 

不确定是否需要在内部 select 或包装器 select 内执行 ON 以进行连接,但您可以尝试 :)

我找到路了。查询将是这样的:

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