2011-12-12 8 views
3

선택적 매개 변수를 사용하여 데이터베이스를 쿼리하는 가장 좋은 방법을 알고 싶습니다. 예를 들어 이름, 위치, 가격, 정렬 등으로 검색했습니다.선택적 매개 변수를 사용하여 복잡한 Doctrine2 쿼리

응용 프로그램의 모델 및 컨트롤러 수준에서 수행해야 할 작업 (Symfony2 btw 사용)은 무엇입니까?

#controller 

$res = $repo->search($serializedData); 

#model/repo->search() 

$data = expand($serializedData); 
$dql = ''; 

if($data['sortby']) 
    $dql .= ..... 

어떤 조언 :

내 생각은 동적 모델의 DQL을 구축하고, 같은 컨트롤러를 통해 그 직렬화 된 매개 변수를 전달했다?

이 코드는 데모 용입니다. 약간 유효하지 않습니다 :)

답변

7

짧은 사용 Doctrine 2 query builder.

더 이상 대답은 잠재적 인 키에 의해 정렬하기위한

#Controller 
// Say if the data was a form submission 
$result = $repo->search($form_data) 

그런 다음 모델의 양식 배열을 검사 할 것이다. 예를 들어 일부 기사를 검색하는 경우.

#Article Repository 

public function search($form_data) 
{ 
    $qb = $this->getEntityManager()->createQueryBuilder(); 

    $qb->select('Article') 
     ->from('SomeBundle:Article'); 

    if($form_data['title']) 
    { 
     $qb->where($qb->expr()->like('Article.title', $qb->expr()->literal('%'.$form_data['title'].'%'); 
    } 
    //For subsequent filters use $qb->andWhere() 

    // You could do more here like pagination, or different hydration (return object or array) 
    return $qb->getQuery()->getResult(); 
} 

체크 아웃 I 추가 정보

+0

감사에 대한 링크 된 문서를! 완벽 해 보인다! –

관련 문제