2012-10-12 6 views
21

Doctrineを使用してSymfony2でカスタムSQLクエリを作成するにはどうすればよいですか?または教義なしでは、私は気にしません。Symfony2&Doctrine:カスタムSQLクエリを作成する

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

ありがとう:

は次のように動作しません。あなたは、エンティティマネージャから直接接続オブジェクトを取得し、それを介して直接SQLクエリを実行することができます

答えて

72

:それは本当に必要でない限り

$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(); 

しかし、私はこれに対して助言するだろう... DoctrineのDQLを扱うことができますほとんどすべてのクエリが必要な場合があります。

公式ドキュメント:http://doctrine-dbal.readthedocs.org/en/latest/reference/data-retrieval-and-manipulation.html

+10

教義でネイティブSQLの提供もあります:http://docs.doctrine-project.org/en/は最新/参考/ native-sql.html – Orbling

+0

魅力のように動作します、ありがとう:) – a1337q

+0

その完璧な、多くの感謝!! – iarroyo

1

あなたはそれが動作します。このコードを実行することができます

$em = $this->getDoctrine()->getEntityManager(); 
$result= $em->createQuery($sql)->getResult(); 
+6

'$ em-> createQuery()'はSQLではなくDQLを実行します。 – loostro

関連する問題