How to update multiple fields using query builder in Doctrine2? - php

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

Related

Check if a value is in one of two columns with doctrine query builder

I'm attempting build a query that will check an entity Project and check two columns either project_owner or project_contributor where project contributor is a Many to One relation.
The query I attempted to make was this (in the project entity repository):
return $this->createQueryBuilder('p')
->where('p.project_owner = :val')
->orWhere(':val in p.project_contributors')
->setParameter('val', $value)
->getQuery()
->getResult()
;
The error I received was the following:
[Syntax Error] line 0, col 75: Error: Expected Doctrine\ORM\Query\Lexer::T_OPEN_PARENTHESIS, got 'p'
Clearly this is the wrong approach. What is the right one? I'm trying to understand the query builder better.
You can make an inner join of the many to one relation, and then filter those.
return $this->createQueryBuilder('p')
->innerJoin('p.project_contributors', 'pc')
->where('p.project_owner = :val')
->orWhere('pc.name = :val')
->setParameter('val', $value)
->getQuery()
->getResult()
;

Symfony Doctrine Group By Query

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

Laravel 5.1 whereNotNull with join not working (returning all data)

I am trying to Select all non empty columns in 'user' table where column name is 'review'.
$applications = DB::table('users')
->join('applications', 'user.update_id', '=', 'applications.id')
->whereNotNull('users.review')
->select('user.id', 'user.rating', 'user.appid', 'user.review', 'applications.title', 'applications.price', 'applications.icon_uri')
->orderBy('user.id','asc')
->paginate(20);
$applications->setPath('');
return $applications;
But return data includes all information of both 'user.review' empty and not empty as well.
I feel there is no effect of whereNotNull() and i found no error in the statement.
I tried moving ->whereNotNull('user.review') this line top and bottom result is same.
I tried even by removing select and orderBy but returns same data.
$applications = DB::table('users')
->join('applications', 'user.update_id', '=', 'applications.id')
->whereNotNull('users.review')
->paginate(20);
$applications->setPath('');
return $applications;
Is there any way to make it work?
if your table is users you are missing an s in the table name, you should write
->whereNotNull('users.review')
same case in the join with the field update_id, otherwise you have to change the table name in the table method

Doctrine query builder, select foreign key

I have this query :
$qb = $this->_em->createQueryBuilder();
$qb->select('DISTINCT c.account')
->from('ThanksWhoProjectBundle:Comment', 'c')
->leftjoin('c.account', 'a')
->where('c.conversation = ?1')
->setParameters(array(1 => $conversation));
return $qb->getQuery()->getResult();
So, the field Comment.account is a foreign key with my entity Account. I just need to retrieve all differents accounts who are in the conversation.
So, i want to only select the field c.account, but with this query have this error :
[Semantical Error] line 0, col 18 near 'account FROM': Error: Invalid PathExpression. Must be a StateFieldPathExpression. (500 Internal Server Error)
How can i do that ?
You need to use DISTINCT on the joined account id:
$qb = $this->_em->createQueryBuilder();
$qb->select('DISTINCT a.id') // note 'a.id'
->from('ThanksWhoProjectBundle:Comment', 'c')
->leftjoin('c.account', 'a')
->where('c.conversation = ?1')
->setParameters(array(1 => $conversation));
return $qb->getQuery()->getResult();
From the official documentation: http://docs.doctrine-project.org/en/latest/reference/dql-doctrine-query-language.html
"Making this possible is very simple. Just add the property shopId to the product entity as any other field mapping property, and so that it corresponds with the actual column in the database table. Make sure you put this property ABOVE the association property “shop”, otherwise it will not work as expected."
http://pietervogelaar.nl/doctrine-2-use-foreign-key-as-field-in-dql/
Note: I am using a custom hydrator. I did run into issues when using this with the default hydrator.
Great, no more unnecessary joins for read only queries! I'm not sure what the effects would be when trying to update the objects in a result set.

How to select fields using doctrine 2 query builder

I have the following query I'm executing in Symfony2 Repository. The query looks like
$q = $this
->createQueryBuilder('m')
->select(array('m.reciever','m.created','m.id','m.subject'))
->where('m.reciever = ?1')
->orderBy('m.id','DESC')
->setMaxResults( '?2' )
->setFirstResult( '?3' )
->setParameter(1,$id)
->setParameter(2,$itemsPerPage)
->setParameter(3,$offset)
->getQuery();
Where reciever, created, id, and subject are fields part of my message entity. I do not need to specify which entity I am selecting from. The error I keep getting is such...
[Semantical Error] line 0, col 12 near 'reciever, m.created,': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
I'm not sure what a state field path expression is or what the syntax might be. It seems like everything should be right.
When you use the select() method, you override the default one which is in $this->createQueryBuilder('m') . That's why you lost the m alias. To avoide this, use an addSelect() or specify the alias in the from() method:
->from('Bundle:Entity', 'ALIAS')
Do you have something like this:=?
$q = $this
->createQueryBuilder()
->select('m.reciever, m.created ,m.id , m.subject')
->from('/Acme/Entity/DemoEntity', 'm')
->where('m.reciever = ?1')
->orderBy('m.id','DESC')
->setMaxResults( '?2' )
->setFirstResult( '?3' )
->setParameter(1,$id)
->setParameter(2,$itemsPerPage)
->setParameter(3,$offset)
->getQuery();
Im not sure but I think you use the array syntax only if you have multiple tables to join together: array('m.reciever, m.created', 'p.user, p.id').
i hope this will help u..
$em = $this->getDoctrine()->getManager();
$q = $em->createQueryBuilder()
->select('m.reciever,m.created,m.id,m.subject')
->from('bundle:entity','m')
->where('m.reciever = ?1')
->orderBy('m.id','DESC')
->setMaxResults( '?2' )
->setFirstResult( '?3' )
->setParameter(1,$id)
->setParameter(2,$itemsPerPage)
->setParameter(3,$offset)
->getQuery();

Categories