Symfony2 using doctrine to summarize _php instances of database query methods

Source: Internet
Author: User
Tags try catch
The example in this paper describes the database query method Symfony2 using doctrine. Share to everyone for your reference, as follows:

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 (' 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 >:p rice ORDER by P.price ASC ')-> ; Setparameter (' Price ', ' 19.99′ '); $products = $query->getresult ();

Note:

(1) To obtain a result can be used:

$product = $query->getsingleresult ();

Using the Getsingleresult () method you need to wrap it up with a try catch statement to ensure that only one result is returned, as 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, rather than writing the value directly into the query statement, to prevent SQL injection attacks, you can also set multiple parameters:

->setparameters (' price ' = ' 19.99′ ', ' name ' = ' Foo ',))

3, the use of doctrine query generator

$query = $repository->createquerybuilder (' P ')->where (' P.price >:p rice ')->setparameter (' Price ', ' 19.99′ )->orderby (' P.price ', ' ASC ')->getquery (); $products = $query->getresult ();

It is hoped that this article is helpful to the PHP program design based on Symfony framework.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.