2012-10-12 3 views
21

Doctrine을 사용하여 Symfony2에서 맞춤 SQL 쿼리를 만들려면 어떻게해야합니까? 또는 교리가 없어도 상관 없습니다.Symfony2 & Doctrine : 맞춤 SQL 쿼리 만들기

은 다음과 같이 작동하지 않습니다 :

$em = $this->getDoctrine()->getEntityManager(); 
    $em->createQuery($sql); 
    $em->execute(); 

감사합니다.

답변

72

당신은 엔티티 관리자에서 직접 연결 개체를 가져, 그 통해 직접 SQL 쿼리를 실행할 수 있습니다 : 그러나

$em = $this->getDoctrine()->getManager(); // ...or getEntityManager() prior to Symfony 2.1 
$connection = $em->getConnection(); 
$statement = $connection->prepare("SELECT something FROM somethingelse WHERE id = :id"); 
$statement->bindValue('id', 123); 
$statement->execute(); 
$results = $statement->fetchAll(); 

, 정말 필요한 않는 한 나는이에 대해 조언을 것 ... 교리의 DQL 처리 할 수 거의 모든 검색어가 필요할 수 있습니다.

공식 문서 : http://doctrine-dbal.readthedocs.org/en/latest/reference/data-retrieval-and-manipulation.html

+10

을 : http://docs.doctrine-project.org/en/ 최신/참조/기본 - sql.html – Orbling

+0

매력처럼 작동, 감사합니다 :) – a1337q

+0

그 완벽한, 많은 감사합니다 !! – iarroyo

1

당신은 작동이 코드를 실행할 수 있습니다

또한 교리의 기본 SQL 조항이
$em = $this->getDoctrine()->getEntityManager(); 
$result= $em->createQuery($sql)->getResult(); 
+6

'$ em-> createQuery()'는 SQL을 실행하지 않고 DQL을 실행합니다. – loostro