복붙노트

[SQL] Symfony2 및 교리 : 만들기 사용자 정의 SQL-쿼리

SQL

Symfony2 및 교리 : 만들기 사용자 정의 SQL-쿼리

어떻게 교리를 사용 Symfony2에서 사용자 지정 SQL 쿼리를 만들 수 있습니까? 또는 교리없이, 난 상관 없어.

이런 식으로 작동하지 않습니다 :

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

감사.

해결법

  1. ==============================

    1.당신은 엔티티 관리자에서 직접 연결 객체를 얻고, SQL 그 통해 직접 쿼리를 실행할 수 있습니다 :

    당신은 엔티티 관리자에서 직접 연결 객체를 얻고, 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 당신이해야 할 수도 있습니다 거의 모든 쿼리를 처리 할 수 ​​있습니다 ...이 무리를 줄 것입니다.

    공식 문서 : https://www.doctrine-project.org/projects/doctrine-dbal/en/2.9/reference/data-retrieval-and-manipulation.html

  2. ==============================

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

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

    $em = $this->getDoctrine()->getEntityManager();
    $result= $em->createQuery($sql)->getResult();
    
  3. from https://stackoverflow.com/questions/12862389/symfony2-doctrine-create-custom-sql-query by cc-by-sa and MIT license