Symfony2使用Doctrine進行資料庫查詢方法執行個體總結_php執行個體

來源:互聯網
上載者:User
本文執行個體講述了Symfony2使用Doctrine進行資料庫查詢方法。分享給大家供大家參考,具體如下:

預定義文中用到的變數:

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

1、基本方法

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

註:

(1) 獲得一個結果可以用:

$product = $query->getSingleResult();

運用 getSingleResult()方法你需要是用try catch語句將它包起來,來保證只返回一個結果,例子如下:

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

(2) setParameter('price', '19.99′);運用這個外部方法來設定查詢語句中的 “預留位置”price 的值,而不是直接將數值寫入查詢語句中,有利於防止SQL注入攻擊,你也可以設定多個參數:

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

3、 運用Doctrine的查詢產生器

$query = $repository->createQueryBuilder('p')->where('p.price > :price')->setParameter('price', '19.99′)->orderBy('p.price', 'ASC')->getQuery();$products = $query->getResult();

希望本文所述對大家基於Symfony架構的PHP程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.