Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Doctrine to query database in Symfony2

Shulou Source: shulou.com Published: 2022-06-03 13:03:00 09月29日 Update

This article mainly introduces Symfony2 how to use Doctrine for database query, the article is very detailed, has a certain reference value, interested friends must read it!

The details are as follows:

The variables used in the predefined text:

$em = $this- > getDoctrine ()-> getEntityManager (); $repository = $em- > getRepository ('AcmeStoreBundle:Product')

1. Basic methods

$repository- > find ($id); $repository- > findAll (); $repository- > findOneByName ('Foo'); $repository- > findAllOrderedByName (); $repository- > findOneBy (array (' name' = > 'foo',' price' = > 19.99)); $repository- > findBy (array ('name' = >' foo'), array ('price' = >' ASC'))

2 、 DQL

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

Note:

(1) A result can be obtained by:

$product = $query- > getSingleResult ()

With the getSingleResult () method, you need to wrap it in a try catch statement to ensure that only one result is returned, as shown in the following example:

-> setMaxResults (1); try {$product = $query- > getSingleResult ();} catch (\ Doctrine\ Orm\ NoResultException $e) {$product = null;}

(2) setParameter ('price',' 19.99'); use this external method to set the value of the "placeholder" price in the query statement instead of writing the value directly into the query statement, which is helpful to prevent SQL injection attacks. You can also set multiple parameters:

-> setParameters (array ('price' = >' 19.99)

3. Query generator using Doctrine

$query = $repository- > createQueryBuilder ('p')-> where ('p.price >: price')-> setParameter (' price', '19.99')-> orderBy (' p.pricegoat, 'ASC')-> getQuery (); $products = $query- > getResult (). These are all the contents of the article "how to use Doctrine for database query in Symfony2". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Tags: Queries methods statements data databases content articles results values examples interests parameters variables multiple guys partners values more benefits generators Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux NVidia Shulou Technology Huawei Shulou Information