I'd like to list my users by birthday, so month and day but not year.
I have this query
SELECT *
FROM user
WHERE birthDate IS NOT NULL
GROUP BY MONTH(birthDate), DAY(birthDate)
But I don't know how to use it with Symfony and Doctrine.
I tried
$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
->createQueryBuilder('user')
->where('user.birthDate IS NOT NULL')
->groupBy('MONTH(user.birthDate), DAY(user.birthDate)')
->getQuery()
->getResult();
And
$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
->createQueryBuilder('user')
->where('user.birthDate IS NOT NULL')
->groupBy('MONTH(user.birthDate)')
->groupBy('DAY(user.birthDate)')
->getQuery()
->getResult();
But in both cases I have an error
[Semantical Error] line 0, col 165 near 'MONTH(birthDate),': Error: Cannot group by undefined identification or result variable.
You haven't set an alias for your values. Here is an updated version :
$result = $em->getRepository("AcmeApplicationBundle:SecurityServiceUser")
->createQueryBuilder('user')
->select(' user.username, MONTH(user.birthDate) AS gBmonth, DAY(user.birthDate) AS gBday')
->where('user.birthDate IS NOT NULL')
->groupBy('gBmonth')
->addGroupBy('gBday')
->getQuery()
->getResult();
This should work fine.
You can use one of these:
format(as.Date,)
or
strftime(source, format)
Related
I'd like to perform query like:
SELECT o.lang, COUNT(o.id) FROM `order` o GROUP BY o.lang;.
I try:
$entityManager->getRepository(Order::class)
->createQueryBuilder('o')
->select(["o.baseLang", "COUNT(o.id)"])
->groupBy("o.baseLang")
->getQuery()
->getResult();
, but I get Error: Invalid PathExpression. Must be a StateFieldPathExpression.
How do I do this?
You put:
$entityManager->getRepository(Order::class)
->createQueryBuilder('o')
->select(["IDENTITY(o.baseLang)", "COUNT(o.id)"])
->groupBy("o.baseLang")
->getQuery()
->getResult();
I'm trying to select all my users and, for each user, count the number of reservations made and incoming. For the moment I have this
$qb = $this->createQueryBuilder('user');
return $qb->select('user')
->leftJoin('user.reservations', 'reservations')
->leftJoin('reservations.marketDate', 'market_date')
->addSelect('COUNT(nb_reservations FROM reservations WHERE market_date.date >= CURRENT_DATE())')
->orderBy('user.name')
->groupBy('user.id')
->getQuery()
->getResult();
But I have this error
[Semantical Error] line 0, col 59 near 'market_date >=': Error: Class
'market_date' is not defined.
Please help me
Try this:
$qb = $this->createQueryBuilder('user');
return $qb->select('user, count(reservations) as count')
->leftJoin('user.reservations', 'reservations')
->leftJoin('reservations.marketDate', 'market_date')
->where('market_date.date >= CURRENT_DATE()')
->orderBy('user.name')
->groupBy('user.id')
->getQuery()
->getResult();
The syntax in the COUNT does not seem correct: the COUNT should not include the whole statement. Try this:
->addSelect('COUNT(nb_reservations) FROM reservations WHERE market_date.date >= CURRENT_DATE()')
I have below sql query running fine,
SELECT completed_by, count(*) AS Total
FROM tasks
WHERE completed_by is not null AND status = 1
GROUP BY completed_by
;
Em am doing it with doctrine query builder, but not working returning an error.
$parameters = array(
'status' => 1,
);
$qb = $repository->createQueryBuilder('log');
$query = $qb
->select(' log.completedBy, COUNT(log) AS Total')
->where('log.Status = :status')
->groupBy('log.completedBy')
->setParameters($parameters)
->getQuery();
and getting below error;
[Semantical Error] line 0, col 21 near 'completedBy,': Error: Invalid
PathExpression. Must be a StateFieldPathExpression.
I know this answer can be late, but I struggled with the exact same problem, and did not find any answer on the internet, and I believe a lot of people will struggle in this same issue.
I'm assuming your "completedBy" refers to another entity.
So, inside your repository, you can write:
$query = $this->createQueryBuilder("log")
->select("completer.id, count(completer)")
->join("log.completedBy", "completer")
->where('log.Status = :status')
->groupBy("completer")
->setParameters($parameters)
->getQuery();
This will compile to something like:
SELECT completer.id, count(completer) FROM "YOUR LOG CLASS" log INNER JOIN log.completedBy completer WHERE log.Status=:status GROUP BY completer
Now, You can do another query to get those 'completers', by their ids.
This is wrong: COUNT(log) AS Total. It should be something like COUNT(log.log) AS Total.
When you want to select a column who is a fk for another table (entity), use the IDENTITY function instead of the column name only.
Example: In your case
$parameters = array(
'status' => 1,
);
$qb = $repository->createQueryBuilder('log');
$query = $qb
->select('IDENTITY(log.completedBy), COUNT(log.something) AS Total')
->where('log.Status = :status')
->groupBy('log.completedBy')
->setParameters($parameters)
->getQuery();
I have to update multiple fields, when I tried to update fields in other table using foreign key id using getRepository() and findOneById() getting bug as unrecognised field, so then later tried to implemented it using query builder. but query doesn't get executing getting bug like undefined fields.
This is the code I have tried:
$this->em
->getRepository('Application_Entity_Company', 'c')
->findOneBy(array('c.userId'=>$post['user_id']));
and
$qb->update('Application_Entity_Company', 'c')
->set('c.name', $post['name'])
->set('c.mobile', $post['mobile'])
->set('c.email', $post['email'])
->where($qb->expr()
->eq('c.userId', ':id'))
->setParameter('id', $post['user_id'])
->getQuery()
->execute();
Here userId is the foreign key. I have to update the fields of user details in user entity using the userId.
The problem is with not obvious usage of set method. Second parameter is expected to be an expression instead of the obvious user input.
For sample incorrectly used set code:
$queryBuilder = $entityManager->getRepository()->createQueryBuilder('u');
$queryBuilder->update()
->set('u.userFirstName', 'Michael')
->where('u.userId = :userId')
->setParameter('userId', 111)
->getQuery()
->execute();
SQL representation:
UPDATE user SET user_first_name = Michael WHERE user_id = 111;
You will get following error:
[Semantical Error] line 0, col 49 near 'Michael WHERE': Error:
'Michael' is not defined.
This is because your database assumes Michael is a table column name which for obvious reasons is not defined.
Solution is to either use \Doctrine\ORM\Query\Expr or by binding parameters:
$queryBuilder = $mapper->getRepository()->createQueryBuilder('u');
$queryBuilder->update()
->set('u.userFirstName', ':userFirstName')// Alternatively $queryBuilder->expr()->literal('Michael')
->where('u.userId = :userId')
->setParameter('userId', 111)
->setParameter('userFirstName', 'Michael')
->getQuery()
->execute();
I have two tables related to each other (main_table OneToMay detail_table). There is a deadline_days field in main table and a create_date in detail_table. I want to select all details which create_date+main.deadline_days are passed base on today date. (This was the scenario)
This is the proper MySQL query which gives me right records
SELECT `D`.* FROM `details_table` AS `D`
INNER JOIN `main_table` AS `M` ON (`D`.`Main_Id` = `M`.`id`)
WHERE DATE_ADD(`D`.`Create_Date`, INTERVAL `M`.`Deadline_days` DAY) <= NOW()
Now in Symfony when I want to create the query using createQueryBuilder it comes with this error
[Syntax Error] line 0, col 165: Error: Expected Doctrine\ORM\Query\Lexer::T_COMMA, got 'M'
This is what I have for now in my query builder
$result = $this->createQueryBuilder('D')
->join('D.Main', 'M')
->where('DATE_ADD(D.Create_Date, INTERVAL M.DeadLine_Days DAY) <= NOW()')
->getQuery()
->getResult();
Any idea how to fix this?
Thanks in advance.
Please do not suggest using native query
This is what I found base on this link (Doctrine Update DQL function signature)
Doctrine2 has function DATE_ADD but does not have INTERVAL param as MySQL, also the unit param should be as string 'DAY'; so the Query should be:
$result = $this->createQueryBuilder('D')
->join('D.Main', 'M')
->where('DATE_ADD(D.Create_Date, M.DeadLine_Days, 'DAY') <= CURRENT_DATE()')
->getQuery()
->getResult();
In doctrine we should use CURRENT_DATE() instead of NOW()