Doctrine2 QueryBuilder Join - php

So, I'm new to doctrine, and I'm trying to do a basic joint, but I guess I'm missing something, on my entities or I don't know for sure.
Doctrine Repository:
$queryBuilder = $this->createQueryBuilder()
->select('c.*, a.*')
->from('My\Entity\CompanyAdminNotes', 'c')
->innerJoin('Administrators','a','a.id = c.admin_id')
->where('c.admin_id = :admin_id')
->setParameter('admin_id', $id);
return $queryBuilder->getQuery()->getResult();
And I get the following error
Message: [Semantical Error] line 0, col 76 near 'a,
My\Entity\CompanyAdminNotes': Error: Identification Variable
Administrators used in join path expression but was not defined
before.
I'm not sure if my query it's wrong or something else isn't set. Can you guys give me a hint?

try to change this:
->innerJoin('Administrators','a','a.id = c.admin_id')
to this:
->innerJoin('My\Entity\Administrators','a','a.id = c.admin_id')
Because It need the path as you done into the from
UPDATE
Trying another solution like this:
$queryBuilder = $this->createQueryBuilder('c')
->select('c, a')
->from('My\Entity\CompanyAdminNotes', 'c')
->innerJoin('My:Administrators','a','a.id = c.admin_id')
->where('c.admin_id = :admin_id')
->setParameter('admin_id', $id);

Related

How to make an Where In subquery in symfony

I'm trying to do this SQL query with Doctrine QueryBuilder:
SELECT * FROM events WHERE NOT id in (SELECT event_id FROM ues WHERE user_id = $userID)
The UserEventStatus has foreign keys from User and event, as well as an integer for status.
I now want to query all events that dont have an entry in UserEventStatus from an particular User.
My function for this in the EventRepository looks like this:
public function getUnReactedEvents(int $userID){
$expr = $this->getEntityManager()->getExpressionBuilder();
$originalQuery = $this->createQueryBuilder('e');
$subquery= $this->createQueryBuilder('b');
$originalQuery->where(
$expr->not(
$expr->in(
'e.id',
$subquery
->select('ues.user')
->from('App/Entity/UserEventStatus', "ues")
->where(
$expr->eq('ues.user', $userID)
)
)
)
);
return $originalQuery->getQuery()->getResult();
}
But i get an error that says:
Error: Method Doctrine\Common\Collections\ArrayCollection::__toString() must not throw an exception, caught ErrorException: Catchable Fatal Error: Object of class Doctrine\ORM\EntityManager could not be converted to string (500 Internal Server Error)
Can anyone help me or point me to right point in the docs? Cause i failed to find something that describes my problem.
And another thing is, that I don't know if its possible, but it would be nice. Can I somehow make direct Object requests? I mean not with the string App/Entity/UserEventStatus but with something like UserEventStatus::class or something.
Thanks for your help in advance. :)
EDIT: It has to be $originalQuery->getQuery()->getResult() of course.
If its like it was with $subquery instead i recive [Semantical Error] line I0, col 41 near 'App/Entity/UserEventStatus': Error: Class 'App' is not defined. (500 Internal Server Error)
Second EDIT:
$expr = $this->getEntityManager()->getExpressionBuilder();
$queryBuilder = $this->createQueryBuilder('e');
$subquery= $this->createQueryBuilder('b')
->select('ues.user')
->from('UserEventStatus', "ues")
->add('where', $expr->eq('ues.user', $userID));
$originalQueryExpression = $expr->not($expr->in('e.id', $subquery));
$queryBuilder->add('where', $originalQueryExpression);
return $queryBuilder->getQuery()->getResult();
Third EDIT: Thanks to #Dilek I made it work with a JOIN. This is the final Query:
$queryBuilder = $this->createQueryBuilder('e')
->leftJoin('App\Entity\UserEventStatus', 'ues', 'WITH', 'ues.user=:userID')
->setParameter('userID', $userID)
->where($expr->orX($expr->not(
$expr->eq('e.id','ues.event')
),
$expr->not($expr->eq('ues.user', $userID)))
);
return $queryBuilder->getQuery()->getResult();
Building AND WHERE into a Query
public function search($term)
{
return $this->createQueryBuilder('cat')
->andWhere('cat.name = :searchTerm')
->setParameter('searchTerm', $term)
->getQuery()
->execute();
}
simple is: ->where('cat.name = :searchTerm')
UPDATE :
I think you need to use where in
$qb->add('where', $qb->expr()->in('ues.user', $userID));
And WHERE Or WHERE

how to write sub-query in symfony doctrine

Am working on a symfony project with backend developed in doctrine & api-platform framework.I need to fetch some details along with checking a field in another table which will be a status. We use this status for handling something in front end.
I tried:-
$qb = $this->createQueryBuilder('contact');
$qb2=$qb;
$sub_query = $qb2->select('field')
->from('OtherTable','g')
->where("'id= '".$personId."'")
->OrderBy('updated_at', 'DESC')
->setMaxResults(1)
->getQuery()
->getResult();
$qb->select("contact.id,
contact.title,
count (distinct person.id) as
number_of_contacts_with_email',(".$sub_query.") as status")
->leftjoin('contact.people', 'person')
->leftJoin('person.jobs', 'jobs')
->groupBy('contact.id, contact.title');
$query=$qb->getQuery();
$result = $qb->getQuery()->getArrayResult();
return $result;
Am getting this error when executing query.
[Semantical Error] line 0, col 59 near 'OtherTable g': Error: Class 'OtherTable' is not defined.
How to write this sub query here?Is there any solution for this?
You should simply use the DQL of the subquery, as example:
// Don't take the query/result instances
$sub_query = $qb2->select('field')
->from('OtherTable','g')
->where("'id= '".$personId."'")
->OrderBy('updated_at', 'DESC')
->setMaxResults(1);
and use
$qb->select("contact.id,
contact.title,
count (distinct person.id) as
number_of_contacts_with_email',(".$sub_query->getDQL().") as status")
->leftjoin('contact.people', 'person')
->leftJoin('person.jobs', 'jobs')
->groupBy('contact.id, contact.title');
Hope this help

Request to MySQL

I need to execute the following request to the MySQL server from symfony.
SELECT count(DISTINCT hotel_id) FROM symfony.search_result where request_id=#requrst_id
Code:
In controller:
$qwery2=$repository->hotelsCount($searchId);
Function:
public function hotelsCount($requestId){
$qb = $this->createQueryBuilder('self');
$qb->select('count(hotel_id)')
->where('self.request_id=:req_id')
->setParameter('self.req_id',$requestId)->getQuery()->getResult();
$rez=$qb->getQuery()->getSingleScalarResult();
var_dump($rez);
return $rez->fetchAll();
}
But i got error:
[Semantical Error] line 0, col 13 near 'hotel_id) FROM': Error: 'hotel_id' is not defined.
Table:
Use count(self.hotel_id) in your select
or count(self.hotelId). And in your where: self.reqId < check the entitys for that
I'm still new myself, so I admit I didn't completely follow your code, but try single quotes around 'hotel_id'
Try this, in this case, entity name is "SearchResult" and bundle name is "AppBundle", change it if is needed.
public function hotelsCount($requestId) {
$qb = $this->createQueryBuilder();
$qb->select('count(p.hotel_id)');
$qb->from('AppBundle:SearchResult', 't')
->where('p.request_id = :id')
->setParameter('id', $requestId);
$count = $qb->getQuery()->getSingleScalarResult();
return $count;
}

Doctrine PHP is already defined

I'm having an issue with doctrine inner joins.
$request = $em->getRepository('FYPFYPDesignBundle:SessionDesign');
$qb = $request->createQueryBuilder('SessionDesign');
$query = $qb
->select('SessionDesign.sessionID', 'SessionDesign.created','fos_user.username', 'fos_user.email', 'fos_user.fcid')
->from('FYPUserBundle:User', 'fos_user')
->innerJoin('fos_user.fcid', 'fos_user', 'ON', 'SessionDesign.sessionID = fos_user.fcid')
->where('fos_user.emailok = true')
->getQuery();
$result = $query->getResult();
The error it gives me is:
[Doctrine\ORM\Query\QueryException]
[Semantical Error] line 0, col 218 near 'fos_user ON SessionDesign.sessionID': Error: 'fos_user' is already defined.
You can't have an alias twice in your querybuilder.
Change:
->from('FYPUserBundle:User', 'fos_user')
->innerJoin('fos_user.fcid', 'fos_user', 'ON', 'SessionDesign.sessionID = fos_user.fcid')
To:
->from('FYPUserBundle:User', 'fos_user')
->innerJoin('fos_user.fcid', 'fcid', 'ON', 'SessionDesign.sessionID = fos_user.fcid')
Assuming fcid is an entity you want to join to.
Note I'm not sure why you're doing what you're doing, but that's what's causing the error.
Edit for more info.
If joining sessiondesign with no doctrine entity relationship (looks like that's what you're doing):
->join('YourBundle:SessionDesign', 's', 'WITH', 's.sessionID = fos_user.fcid')

Symfony2 SymBlog tutorial : [Semantical Error] line 0, col 15 near 'c.post = :post_id': Error: Class 'c' is not defined.

I was following the Symfony2 blog tutorial part 4
and I encountered this error when I tried to query the post's comments:
public function postAction($id) {
$em = $this->getDoctrine()->getEntityManager();
$post = $em->getRepository('BlogBundle:Post')->find($id);
if (!$post) {
throw $this->createNotFoundException('Unable to find Blog post.');
}
$comments = $em->createQueryBuilder('c')
->select('c')
->where('c.post = :post_id')
->addOrderBy('c.created')
->setParameter('postId', $id)
->getQuery()
->getResult();
return $this->render('BlogBundle:Default:post.html.twig', array(
'post' => $post,
'comments' => $comments
));
}
I get the following error:
"[Semantical Error] line 0, col 15 near 'c.post = :post_id': Error:
Class 'c' is not defined."
The link to the tutorial you gave doesn't work for me so I can't see the context of what your are doing but...
The parameter for createQueryBuilder() is the name of the table so you have a table called 'c'. This seems an odd name for a table.
In your query your should be selecting fields from the table, not selecting the table.
Hope that helps but if you can give a link that works I can better see what you're trying to acheive.
You can not call createQueryBuilder directly on EntityManager because it does not know what c is. This is because you just copy&paste without context and code was invoked inside repository class in tutorial. Not in controller.
Try this
$comments = $em->getRepository('BlogBundle:Comment')->createQueryBuilder('c')
->select('c')
->where('c.post = :post_id')
->addOrderBy('c.created')
->setParameter('postId', $id)
->getQuery()
->getResult();
Or add method for fetching comments into PostRepository similarly as in tutorial.
You should speify the Entity you need:
$comments = $em->createQueryBuilder('c')
->from('BlogBundle:Comment', 'c') // I suppose your entity is Comment
->select('c')
->where('c.post = :post_id')
->addOrderBy('c.created')
->setParameter('postId', $id)
->getQuery()
->getResult();

Categories