简体   繁体   中英

How to implement Complex SQL Query in Doctrine or ORM

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 ie 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.

$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.

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM