2014-07-21 2 views
0

카테고리별로 게시물을 가져와 표시되는 것을 제외하고 최대 제한을 설정하는 작동하는 queryBuilder가 있습니다.Symfony2 -이 querybuilder를 어떻게 단순화 할 수 있습니까?

질문 :이 queryBuilder를 어떻게 단순화 할 수 있습니까?

쿼리에서 나는 2 개의 테이블 (카테고리/OneToMany/ManyToOne 관계로 연결된 게시물)을 조인 할 필요가없고 컨트롤러에서 $ category를 설정하고있다. 리팩터링의 더 나은 방법이있다. 이?

queryBuilder

public function getRelatedPosts($exceptPost, $limit, $category) 
{ 
return $this 
->createQueryBuilder('post') 
->leftJoin('post.category','category') 
->where('post != :exceptPost') 
->setParameter('exceptPost', $exceptPost) 
->andWhere('category = :category') 
->setParameter('category', $category) 
->orderBy('post.createdAt', 'DESC') 
->setMaxResults($limit) 
->getQuery() 
->execute(); 
} 

컨트롤러 queryBuilder

public function getRelatedPosts($exceptPost, $limit, $category) 
{ 
    return $this 
     ->createQueryBuilder('post') 
     ->where('post != :exceptPost') 
     ->andWhere('post.category = :category') 
     ->setParameter('exceptPost', $exceptPost) 
     ->setParameter('category', $category) 
     ->orderBy('post.createdAt', 'DESC') 
     ->setMaxResults($limit) 

     ->getQuery() 
     ->execute(); 
} 
+0

조인을 제거하고 * category *에 대한 쿼리의 where 절을'-> andWhere ('post.category = : category')'로 변경 한 다음 매개 변수를'-> setParameter ('category', $ category-> getId())'? 참조 된 컬럼 이름이 'id'라면 – Javad

+0

위의 작업 쿼리를 업데이트했습니다. 그리고 조인을 제거, 내가 컨트롤러에서 카테고리를 설정하는 것을 없애 버릴 수있는 방법이 있습니까? 'category = $ post-> getCategory();'그리고 그것을 전달합니까? – Kincsem

답변

1

업데이트

public function showAction($slug) 
{ 
    $post = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post') 
     ->findOneBy(array(
      'slug' => $slug 
     )); 

    if (null === $post) { 
     throw $this->createNotFoundException('Post was not found'); 
    } 

    $category = $post->getCategory(); 

    $posts = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post') 
     ->getRelatedPosts($post, 4, $category); 

    return array(
     'post' => $post, 
     'posts' => $posts 
    ); 
} 

내가 스와 아니다
컨트롤러

public function showAction($slug) 
{ 
    $post = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post') 
     ->findOneBy(array(
     'slug' => $slug 
    )); 

    if (null === $post) { 
     throw $this->createNotFoundException('Post was not found'); 
    } 

    $posts = $this->getDoctrine()->getRepository('AcmeDemoBundle:Post') 
     ->getRelatedPosts($post, 4); 

    return array(
     'post' => $post, 
     'posts' => $posts 
    ); 
} 

저장소

public function getRelatedPosts($exceptPost, $limit) 
{ 
    return $this 
    ->createQueryBuilder('post') 
    ->where('post.id != :exceptPost') 
    ->andWhere('post.category = :category') 
    ->setParameter('exceptPost', $exceptPost->getId()) 
    ->setParameter('category', $exceptPost->getCategory()->getId()) 
    ->orderBy('post.createdAt', 'DESC') 
    ->setMaxResults($limit) 
    ->getQuery() 
    ->getResult(); 
} 

또한의 조인 쿼리에서이 문제를 구축 할 수 있습니다 : 이것이 당신이 찾고 있지만, 이런 식으로 뭔가를 할 수 있습니다 어떤 경우 재 자체 테이블 또는 SELECT ... IN (...); 관심이 있으시면

관련 문제