Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

doctrine: QueryBuilder vs createQuery?

Tags:

doctrine-orm

In Doctrine you can create DQL in 2 ways:

EntityManager::createQuery:

$query = $em->createQuery('SELECT u FROM MyProject\Model\User u WHERE u.id = ?1'); 

QueryBuilder:

$qb->add('select', 'u')    ->add('from', 'User u')    ->add('where', 'u.id = ?1')    ->add('orderBy', 'u.name ASC'); 

I wonder what the difference is and which should I use?

like image 248
never_had_a_name Avatar asked Apr 20 '10 21:04

never_had_a_name


People also ask

Is Query builder an ORM?

The ORM's query builder provides a simple to use fluent interface for creating and running queries.

What is doctrine SQL?

Doctrine features a powerful query builder for the SQL language. This QueryBuilder object has methods to add parts to an SQL statement. If you built the complete state you can execute it using the connection it was generated from. The API is roughly the same as that of the DQL Query Builder.

How does query builder work?

Using Query Builder, you can search and filter database objects, select objects and columns, create relationships between objects, view formatted query results, and save queries with little or no SQL knowledge.

What is Query builder in C#?

SQL query builder, written in c#, helps you build complex queries easily, supports SqlServer, MySql, PostgreSql, Oracle, Sqlite and Firebird. sqlkata.com.


2 Answers

  1. DQL is easier to read as it is very similar to SQL. If you don't need to change the query depending on a set of parameters this is probably the best choice.

  2. Query Builder is an api to construct queries, so it's easier if you need to build a query dynamically like iterating over a set of parameters or filters. You don't need to do any string operations to build your query like join, split or whatever.

like image 65
jackbravo Avatar answered Sep 19 '22 17:09

jackbravo


Query builder is just, lets say, interface to create query... It should be more comfortable to use, it does not have just add() method, but also methods like where(), andWhere(), from(), etc. But in the end, it just composes query like the one you use in the createQuery() method.

Example of more advanced use of query builder:

$em->createQueryBuilder()             ->from('Project\Entities\Item', 'i')             ->select("i, e")             ->join("i.entity", 'e')             ->where("i.lang = :lang AND e.album = :album")             ->setParameter('lang', $lang)             ->setParameter('album', $album); 
like image 28
Martin Kočička Avatar answered Sep 18 '22 17:09

Martin Kočička