The Blog

Executing SQL directly in Symfony2 Doctrine Posted on

Ok, so I’m moving project from non framework PHP to Symfony2, and it goes very nice, except of Doctrine, I’m sure it’s me. I’ve been using MySQL for last 8 years and DQL vs SQL to me feels like i.e. taking snowboard for the first time, after skiing for 30 years. What I do after 30 min. of trying. I’m going back to rental place and I switch to skis. Below one can find skis.

use Doctrine\ORM\EntityRepository;

class ProductRepository extends EntityRepository
{

$stmt = $this->getEntityManager()
->getConnection()
->prepare('select * from product where 1');
$stmt->execute();
$result = $stmt->fetchAll();

return $this->render('Test1Bundle:Default:index.html.twig', array('name' => 'Showig '. print_r($result,true)));
}

Or if you do not want to use class try this.

$stmt = $this->getDoctrine()->getEntityManager()
   ->getConnection()
    ->prepare('select * from product where 1');
$stmt->execute();
$result = $stmt->fetchAll();

Or this

$rsm = new ResultSetMapping;
        $rsm->addScalarResult('optionname', 'option');
        $rsm->addScalarResult('answers', 'count');

        return $this->_em->createNativeQuery('
       SELECT
         qo.title as optionname,
         COUNT(qap.answer_id) as answers
      FROM
         quiz_answer_option qap
         INNER JOIN quizoption qo ON qo.id = qap.option_id
         INNER JOIN quizquestion qq ON qq.id = qo.quizquestion_id
      WHERE
         qq.active
         AND qq.id = :quizquestionid
      GROUP BY qap.option_id
      ORDER BY qo.number asc
        ', $rsm)
       ->setParameter('quizquestionid', $quizquestion->getId())
       ->getResult();

For more look HERE

This entry was posted in Frameworks, PHP, Symfony3. Bookmark the permalink.

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *



CAPTCHA
Change the CAPTCHA codeSpeak the CAPTCHA code