How to implement Complex SQL Query in Doctrine or ORM

1.4k views Asked by At

I am using Symphony 2.3.3 and is new to Doctrine and ORM. I read a lot about doctrine entity manager, DBAL, DQL etc. I have the following query that I have built in SQL and now want to implement it by using any of the above methods i.e. easy one.

select su.sensor_id, su.user_id
, usr.contact_id, usr.enabled as user_status
, ctct.Email1, ctct.Email2, ctct.active as contact_status, ctct.contacttype_id
, ctctty.`type` as contact_type, ctctty.active as contact_type_status
from sensor_users su, `Users` usr, contacts ctct, contact_types ctctty
where su.user_id = usr.id
and usr.contact_id = ctct.id
and ctct.contacttype_id = ctctty.id
and usr.enabled = 'Y'
and ctct.active   = 'Y'
and ctctty.active = 'Y'
and su.sensor_id = 123;

Early reply is highly appreciated on how to use it. For DBAL, how to get the connection from the parameters.yml.

Regards.

2

There are 2 answers

1
ybert On
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery(
    'SELECT p
    FROM AcmeStoreBundle:Product p
    WHERE p.price > :price
    ORDER BY p.price ASC'
)->setParameter('price', '19.99');

$products = $query->getResult();

This is a simple example from symfony documentation. You can do what you want with dql queries.

0
ybert On
$query = $em->createQuery(
'SELECT su, usr, ctct, ctctty
FROM Yoursensor_usersClass su
JOIN su.YourfieldToJoinUser usr
JOIN usr.yourFielToJoinContacts ctct
JOIN ctct.yourFieldToJoinContactType ctctty
WHERE usr.enabled = :y
and ctct.active   = :y
and ctctty.active = :y
and su.sensor_id = :nb'
)->setParameter(array(
'y' => 'Y',
'nb' => '123'));

It should be that. Just replace by entities managing your dbs tables.