Doctrine queryBuilder setParamater - doctrine-orm

I'm having a problem using Parameters in the Doctrine queryBuilder.
Here's my code:
$queryBuilder
->select('id', 'value')
->from('test')
->where('id = :id')
->setParameter('id', '1', 'integer')
;
This creates:
SELECT id, value FROM test WHERE id = :id
However the setParameter is not applied when I use
$stmt = $conn->query($queryBuilder);
Getting this Error:
"Fatal error: Uncaught exception 'Doctrine\DBAL\Driver\Mysqli\MysqliException' with message 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':id'..."
What am I missing?
Using this works, but I would prefer to integrate the parameters directly in the queryBuilder:
$stmt = $conn->prepare($queryBuilder);
$stmt->bindValue("id", "1", "integer");
$stmt->execute();
Any hints would be great.

It's possible to directly execute the querybuilder, this will attach the paramaters correctly.
Example:
$queryBuilder = $conn->createQueryBuilder();
$queryBuilder
->select('id', 'value')
->from('test')
->where('id = :id')
->setParameter('id', '1', 'integer');
$queryBuilder->execute();

Related

Complex QueryBuilder expresion in createQuery() with Sonata Admin

I'm using Symfony 4.2 and Sonata Admin bundle and I'm trying to display a specific list in one of my admin list view.
I want to display the lastest user by group. I created the SQL query and I'm now trying to translate it to QueryBuilder.
SELECT * FROM users
WHERE (created_at, group_id) IN (
SELECT MAX(created_at), group_id
FROM users
GROUP BY group_id)
My createQuery function in my Sonata Admin class :
public function createQuery($context = 'list')
{
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
$expr = $em->getExpressionBuilder();
$subQuery = $em->createQueryBuilder()
->select('MAX(c.createdAt), c.group')
->from('ApiBundle:Configuration', 'c')
->groupBy('c.group')
->getDQL();
$query = parent::createQuery($context);
$alias = $query->getRootAlias();
$query->where($expr->in('('.$alias.'.createdAt, '.$alias.'.group)', $subQuery));
}
Unfortunately it is not working and I'm not sure it's the right way to do it.
I could make it work with only selecting the createdAt in the in() expression but it's not what I want to have at the end.
Here is the error I got.
[Syntax Error] line 0, col 77: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_PARENTHESIS, got ','
How can I make it work using QueryBuilder ?
Thank you.

How to add a property to an object returned by Doctrine

I am doing the following Query in doctrine:
$result = $conductores
->select('c.id, c.runFormateado, c.nombres, c.apellidos, c.requisitosWebcontrol, e.nombre as empresa, c.createdAt, c.updatedAt')
->innerJoin('c.empresa', 'e', 'ON')
->getQuery()
->getResult();
I need to modify each record of that result set to have 2 more properties that I will use later.
I tried by adding "null as new_property" in the select method call but doctrine shows an error.
How can I do it?
Regards
Jaime
You can try something like this:
$result = $conductores
->select('c.id, c.runFormateado, c.nombres, c.apellidos, c.requisitosWebcontrol, e.nombre as empresa, c.createdAt, c.updatedAt, \'\' as new_property_1, \'\' as new_property_2')
->innerJoin('c.empresa', 'e', 'ON')
->getQuery()
->getResult();
You can try this using MySQL directly in your database, to see how this works.
Example: Assuming you have a User table
select Id, FirstName, LastName, '' as new_colum_1, '' as new_column_2
from Users;
I hope this works for you.

Error: Expected Literal, got 'SELECT'

I'm trying to add a method to a doctrine repository
public function getOpenedImport(Uftts $fattura){
$dql = "SELECT F.importoFattura*C.segnoNumerico - (SELECT SUM(I.importo*C2.segnoNumerico)
FROM MyAppDomain:Incas I
INNER JOIN MyAppDomain:Cjcau AS C2 ON C2.codice = I.causale
WHERE I.annoDocumento = F.annoDocumento AND I.numeroDocumento = F.numeroDocument)
FROM MyAppDomain:Uftts F
INNER JOIN MyAppDomain:Cjcau C ON C.codice = F.causale
WHERE F.annoDocumento = :annoDocumento AND F.numeroDocumento = :numeroDocumento";
$query = $this->getEntityManager()->createQuery($dql);
$query->setParameters(['annoDocumento' => $fattura->getAnnoDocumento(),
'numeroDocumento' => $fattura->getNumeroDocumento()]);
return $query->getSingleScalarResult();
}
This query if executed on my Sql Server 2008 returns the expected result, but using doctrine i get
Error: Expected Literal, got 'SELECT'
I can't find out what's wrong.
$dql variable is not valid DQL. I am not sure how to make it valid also.
You can write plain SQL and run
$this->getEntityManager()->getConnection()->executeQuery($query, $params)
it's a wrapper over PDO, so you will get result like you were performing simple PDO query.

What is wrong with doctrine2 query builder - expected literal

I am using Doctrine 2 within ZF2 code and I am trying to write update query.
Code is like this:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->update('Application\Entity\Groups', 'group')
->set('group.state', '?1')
->set('group.modified', '?2')
->where($qb->expr()->eq('group.id', '?3'))
->setParameter(1, \Application\Entity\Groups::STATE_DELETED)
->setParameter(2, $modified)
->setParameter(3, $group_id);
Doctrine2 complains about query. Exact error message is:
(string) [Syntax Error] line 0, col 87: Error: Expected Literal, got 'group'
It seems that keyword group created problems. When I used gr alias instead of group it worked fine.
So, DQL bellow worked:
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->update('Application\Entity\Groups', 'gr')
->set('gr.state', ':state')
->set('gr.modified', ':modified')
->where($qb->expr()->eq('gr.id', ':group_id'))
->setParameter('group_id', $group_id)
->setParameter('state', \Application\Entity\Groups::STATE_DELETED)
->setParameter('modified', $modified);

doctrine 2 query builder and join tables

I'm trying to get all comments for each post in my home page
return
$this->createQueryBuilder('c')
->select('c')
->from('Sdz\BlogBundle\Entity\Commentaire' ,'c')
->leftJoin('a.comments' ,'c')->getQuery()->getResult() ;
but I'm getting this error
[Semantical Error] line 0, col 58 near '.comments c,': Error:
Identification Variable a used in join path expression but was not defined before.
PS : The mapping is correct because I can see the page article with its comments.
In case this is still giving you problems, here is your query using the syntax found in the examples in the Doctrine 2.1 documentation.
I'm assuming your query resides in a custom repository method, and that 'a' is an abbreviation for 'Article'.
$em = $this->getEntityManager();
$qb = $em->createQueryBuilder();
$qb->select(array('a', 'c'))
->from('Sdz\BlogBundle\Entity\Article', 'a')
->leftJoin('a.comments', 'c');
$query = $qb->getQuery();
$results = $query->getResult();
return $results;