How I can convert normal SQL query in to doctrine ORM - php

I just started studying Symfony 3.4 and Doctrine ORM. I need to take count of users. I tested with the normal query it is working fine. How can I convert the normal query into Doctrine ORM? Any help would be appreciated.
"SELECT count(DATE_FORMAT(application.reviewed_at, '%Y-%m-%d')) AS count, user_id FROM application WHERE user_id = 6 AND DATE(reviewed_at) = CURDATE() GROUP BY DATE(reviewed_at)";
I tried below code. It is not working.
$qb = $em->createQueryBuilder();
$entries = $qb->select("count(DATE_FORMAT(application.reviewed_at, '%Y-%m-%d')) AS count", "user_id")
->where("user_id = 6", "DATE(reviewed_at) = CURDATE()")
->from('AppBundle\Entity\Application', 'u');
->groupBy("DATE(reviewed_at)");
->getQuery()
->getResult();

Simply put, Doctrine ORM is not intended to transform SQL queries back into DQL. DQL is a query language that can be translated into multiple vendor-specific SQL variants, so this is a one-way transformation from DQL to SQL.
Thus, if you have just a SQL query, it could be a good idea to use just that, using Doctrine DBAL. Of course, you'd probably have to deal with result set mappings, but there could be no need to drag all the ORM stuff into your code.
What you're doing here is essentially building a DQL query using the Doctrine's QueryBuilder API. The FROM part is absolutely correct, but those using the DATE_FORMAT and DATE functions look wrong to me. Since DQL translates to several different SQL implementations, depending on the driver you're using, it needs a compatibility layer because functions such as DATE_FORMAT, DATE and CURDATE are not common for all the platforms.
First, take a look at the documentation for user-defined functions. For example, the DATEDIFF() function in MySQL is a good example. If it turns out that no one has already implemented support for the functions you're using, that's a good place to start, since it basically describes how to implement an extension for the Doctrine Query Language (DQL).
Second, there's a good chance that the functions you're using are already implemented in some of the third-party libraries, such as OroCRM's or Benjamin Eberlei's Doctrine extension collections.
Also, if you're selecting an aggregation or a function call result, it's always a good idea to alias it. What you could try here is use the $qb->expr() function subset to limit the DQL to a more strict grammar.

It is important to remember that Doctrine DQL is not an SQL dialect. It is a custom language that attempts to look close to SQL, but it operates with Doctrine entities and associations, not with database tables and columns. Of course at the end it transforms into SQL, but until this transformation you need to stay within DQL syntax.
One of reasons why your query did not work is an attempt to use native SQL (MySQL to be true) functions inside DQL query. DQL have no such functions and you have 2 ways to go at this point:
Rewrite your query in a way that it will be compatible with Doctrine. It may involve updates for your database scheme. In your particular case you may want to convert reviewet_at column from whatever it is now (timestamp I suppose) into date type that allows direct date comparisons. It will let you to get rid of custom MySQL date transformation functions and will make your query compatible with Doctrine
You can choose a harder path and implement all necessary custom functions directly in Doctrine. It is not a simple thing, but Doctrine is flexible enough to provide you with such ability. There is good article into Doctrine documentation about this topic if you will be interested.

Try to give a go to this:
public function select()
{
$queryBuilder = $this->createQueryBuilder('a');
$queryBuilder
->addSelect(['a.user_id', $queryBuilder->expr()->count('a.reviewed_at')])
->where('a.user_id = :idUser')
->andWhere('a.reviewed_at = :date')
->setParameters([
'idUser' => 6,
'date' => new \DateTime(),
])
->groupBy('a.reviewed_at')
;
return $queryBuilder
->getQuery()
->getResult()
;
}

Related

doctrine2 querybuilder not between

I'd like to make a MySQL query with doctrine2 QueryBuilder (Symfony 3.4 app) with a NOT BETWEEN statment.
The doctrine provide a ->expr()->between(..) but not ->expr()->notBetween(..)
Is there a way to negate the between with the query builder.
I don't want to use a native or a DQL query if possible.
Note: I think a possible solution is to use ->expr()->lt(..) and/or ->expr()->gt(..) but I want to know if notBetween is possible.
Thanks
Expected:
A NOT BETWEEN SQL statement with Doctrine2 QueryBuilder
After some attempts, I found a suitable solution for me:
The QueryBuilder provide a ->expr()->not(...), so in this case this is possible:
$qb->exp()->not($qb->between('field', 'from', 'to')
SQL result:
NOT (BETWEEN field from AND TO)

Is there a way to add a LIMIT to an UPDATE query in Doctrine ORM?

I am using Doctrine 2.5.x and I am having problems with getting the LIMIT clause to work for UPDATE queries. It always updates all matched records (i.e. it seems to ignore the LIMIT clause).
setMaxResults() seems to have no effect when used together with UPDATE queries.
As a quick workaround I am using a native MySQL query but that cannot be the best solution.
I tried these examples but none are working:
Doctrine update query with LIMIT
https://recalll.co/app/?q=doctrine2%20-%20Doctrine%20update%20query%20with%20LIMIT
QueryBuilder with setMaxResults() (does not work):
$qb = $em->createQueryBuilder();
$query = $qb->update('\Task\Entity', 't')
->set('t.ClaimedBy', 1)
->where('t.Claimed IS NULL')
->getQuery();
$query->setMaxResults(20);
$this->log($query->getSQL());
Hope someone can help in finding a better solution than a native query. It takes away the whole benefit of the ORM.
Is it even possible to use a LIMIT clause in an UPDATE statement?
In short, no, because the SQL specification does not support UPDATE ... LIMIT ..., so none of the ORM trying to achieve portability should allow you to do it.
Please also have a look at MySQL Reference Manual itself stating that UPDATE ... LIMIT ... is not a standard SQL construction:
MySQL Server supports some extensions that you probably will not find in other SQL DBMSs. Be warned that if you use them, your code will not be portable to other SQL servers. In some cases, you can write code that includes MySQL extensions, but is still portable, by using comments of the following form:
SQL statement syntax
The ORDER BY and LIMIT clauses of the UPDATE and DELETE statements.
So by essence because what you are trying to achieve is not standard SQL the ORM will not have a portable way to implement it and will probably not implement it at all.
Sorry, but what you are trying to achieve is not possible through DQL, because:
Ocramius commented on Sep 2, 2014
DQL doesn't allow limit on UPDATE queries, as it is not portable.
As suggested in this issue of DoctrineBundle repository by its owner, Marco Pivetta (he also happen to be the owner of the ORM repository).
Further information, although it might needs a good link to the right ISO specification documentation that is sadly not freely available:
The ISO standard of UPDATE instruction do not allow LIMIT in an UPDATE, where SELECT is, of course, an instruction that does allow it.
As you were raising it by yourself, the purpose of an ORM is to not write pure SQL in order to have it cross DBMS compatible. If there is no possibility to make it that way, then it makes sense that the ORM does not implement it.
Also note that on other SQL variant than MYSQL, the limit is actually part of the SELECT clause:
select * from demo limit 10
Would translate in a SQL Server to
select top 10 from demo
Or in Orcale to
select * from demo WHERE rownum = 1
Also see: https://stackoverflow.com/a/1063937/2123530
As b.enoit.be already stated in his answer, this is not possible in Doctrine because using LIMIT's in an UPDATE statement is not portable (only valid in MySQL).
Hope someone can help in finding a better solution than a native query. It takes away the whole benefit of the ORM.
I would argue that you are mixing business rules with persistence (and the ORM does not play well with that, luckily).
Let me explain:
Updating an entity's state is not necessarily a business rule. Updating max. 20 entities is (where does that 20 come from?).
In order to fix this, you should properly separate your business rules and persistence by separating it into a service.
class TaskService
{
private $taskRepository;
public function __construct(TaskRepository $taskRepository)
{
$this->taskRepository = $taskRepository;
}
public function updateClaimedBy()
{
$criteria = ['Claimed' => null];
$orderBy = null;
// Only update the first 20 because XYZ
$limit = 20;
$tasks = $taskRepository->findBy($criteria, $orderBy, $limit);
foreach($tasks as $task) {
$task->setClaimedBy(1)
}
}
}

Use Laravel Eloquent all the time?

Is there any advantages of using Laravel Eloquent all the time instead of raw SQL?
I have a habit of writing SQL first in phpMyAdmin to check the relationship and then translate it Eloquent ORM.
Sometime translating to Eloquent ORM is painful and time consuming especially translating from long complicated SQL query. I am able to write fast in SQL than using Eloquent ORM.
The most important benefit of using the Query Builder is abstraction, which usually leads to less code. Also, because the builder is database agnostic, it allows to seamlessly switch the RDBMS, for example from MySQL to PostgreSQL (but this only applies in some cases as there are some things that are database specific and cannot be abstracted).
Using it in conjunction with Eloquent offers the added benefit of having the results converted into Eloquent models, which means you can use relations, mutators, accessors and all the other benefits that Eloquent models offer. For example:
$users = DB::select('select * from users');
Will return an array of stdClass objects, while the following:
$users = User::all();
Will return a collection of Eloquent models on which you can get relations:
foreach ($users as $user) {
$user->projects();
}
Or make changes and save the entry:
$user->name = 'Bob Dylan';
$user->save();
These things can be done with the raw query approach, by manually creating a collection of models like so:
// Replace the stdClass items with User models
foreach ($users as &$user) {
$user = new User($user);
}
// Create a Collection with the results
$users = new Illuminate\Support\Collection($users);
But it adds complexity which is already implemented by Eloquent.
A good example of how abstraction leads to less code would be this:
User::whereIn('id', [1, 7, 100]);
Which is less code than the equivalent:
DB::select('select * from users where id in (?)', [implode(',', [1, 7, 100]);
The important thing to take in consideration when using raw queries that make use of user input, is to always use bindings to avoid leaving yourself open to SQL Injection.
That being said, there are cases where, as you said, it's a pain to convert queries to use the Query Builder, because the builder has limitations given that it's database agnostic.
There is no problem with using raw queries. I usually use a combination of both Query Builder for simpler queries that need Eloquent models and raw queries for more complex operations, where it just makes sense not to use DB::raw allover the place just to use the Query Builder. So taking into account the things I said above, it just boils down to preference really.
There's no problem and you should use raw SQL if that suits you better. Eloquent's goal is to simplify queries.
The only thing you have to take care of is to prepare everything.

Builder for ElasticSearch query DSL in Yii2 (or standalone)

As far as I can see, the only way to make a query to ElasticSearch in Yii2 is to run ElasticModel::find()->query($query), where $query is a complex array containing the actual query written in ElasticSearch query DSL.
The query is huge and quickly becomes unmanageable. For SQL Yii2 provides a powerful query builder class that supports tons of useful methods like andWhere(). For ElasticSearch everything goes into one gigantic query expression, very much like building an SQL expression string by hand.
Is there any high-level wrapper for ElasticSearch query DSL for Yii2? If not, is there a standalone library with similar functionality?
If you intend to build for version 1.6 of elastic, I have created a query builder for my company and published it here
You will use it as a standalone query builder, and at the end you will need to get the final query array and pass it to the query executer.
To install it, you can simply use composer composer require itvisionsy/php-es-orm or download the zipped version here.
The link above contains some examples, and here is a copy:
//build the query using different methods
$query = \ItvisionSy\EsMapper\QueryBuilder::make()
->where('key1','some value') //term clause
->where('key2',$intValue,'>') //range clause
->where('key3','value','!=') //must_not term clause
->where('key4', ['value1','value2']) //terms clause
->where('email', '#hotmail.com', '*=') //wildcard search for all #hotmail.com emails
->sort('key1','asc') //first sort option
->sort('key2',['order'=>'asc','mode'=>'avg']) //second sort option
->from(20)->size(20) //results from 20 to 39
->toArray();
//modify the query as you need
$query['aggs']=['company'=>['terms'=>['field'=>'company']]];
//then execute it against a type query
$result = TypeQuery::query($query);
//i am not sure about Yii way to execute, according to the question, it should be:
$result = ElasticModel::find()->query($query);
The package also include a simple ElasticSearch ORM class which maybe useful for you. Take a look at it here.
Hope this helps you...

Doctrine DQL execute passing params

I used this DQL in Doctrine
$q->update('product')
->set('quantity','?')
->where('id=?');
$q->execute(array(20,5));
I check the server for the query and this the generated sql
UPDATE product SET quantity = '20', updated_at = '5'
WHERE (id = '2010-04-26 14:34);
So I need to know why the arguments aren't in the correct places?
I got caught by the exact same bug myself a few days ago. I believe it's caused by a bug in the Timestampable behavior. I'm guessing you have it enabled in the Product model, and Doctrine adds the updated_at field into the series of fields to update (SET) and doesn't pay attention to the fact that you have SQL parameters after that (in the where clause). This bug never comes up when doing SELECTs because Timestampable isn't involved.
The only solution I found is to supply the parameters as you build the query rather than in the execute's array parameter and Doctrine won't get confused. Like this:
$q->update('product')
->set('quantity', 20)
->where('id = ?', 5);
$q->execute();
However if you need to run the same query many times with different values, you'd be losing the performance benefits of separate prepare & execute phases. It appears this is the only solution.
Potentially better solution without performance loss:
I have not verified this, however, I would hope that bug would not surface if you used named parameters instead of the anonymous ? placeholders. Doctrine's support for named parameters is described here: http://www.doctrine-project.org/documentation/manual/1_2/en/dql-doctrine-query-language
EDIT: I have since tried the alternate approach with named parameters and unfortunately the bug remains. Doctrine gives an error saying you can't mix named and anonymous parameters in the same query. This really should have been fixed a long time ago IMO.

Categories