Is there any way to alias fields when using partial object syntax in Doctrine 2?
I know I can do this:
$this->createQueryBuilder('user')->select([
'user.id AS id',
'user.firstName AS first_name',
'user.lastName AS last_name',
'user.email AS email',
'user.dateCreated AS date_created'
])->getQuery()->getArrayResult();
However I need to use the partial object syntax in order for doctrine to retrieve the result in a nested relational heirarchy:
$this->createQueryBuilder('team')
->select('PARTIAL team.{id, name, dateCreated}, s, PARTIAL e.{id, name}')
->innerJoin('team.session', 's')
->innerJoin('s.event', 'e')
->getQuery()->getArrayResult();
I dug around in Doctrine\ORM\Internal\Hydration\ArrayHydrator but didn't see any hooks or anything, and it doesn't look like Doctrine has a postSelect event or something that would allow me to implement my own mutation.
Thanks for any help!
Not very efficient, but I ended up subclassing the ArrayHydrator and mutating the keys myself.
Hopefully there is a better way, if not I hope this helps someone
The problem is not just about alias, it's also about bracket. Basically, Partial object syntax is very poor and does not allow aliases or brackets. It expects for a coma or the end of the list, and everything else will throw a syntax error.
I wanted to retrieve a partial object collection using a SUM() function like this
public function findByCompetition(array $competition)
{
$competitionField = $competition['field'] ?? 'Id';
$competitionValue = $competition['value'] ?? 0;
$teamsCompStatsByComp = $this->createQueryBuilder('t')
->select('partial t.{Id, competitionId, competitionOldId, teamId, teamOldId, SUM(goalsAttempted) goalsAttempted}')
->where('t.'.$competitionField.' = ?1')
->groupBy('t.teamId')
->orderBy('t.Id', 'ASC')
->setParameter('1', $competitionValue)
->getQuery()
->getResult()
;
return new ArrayCollection($teamsCompStatsByComp);
}
But got the same error
[Syntax Error] line 0, col 85: Error: Expected Doctrine\ORM\Query\Lexer::T_CLOSE_CURLY_BRACE, got '('
I had to retrieve data as an array, use IDENTITY() on Foreign Key, then manually hydrate my entities
public function findByCompetition(array $competition)
{
$competitionField = $competition['field'] ?? 'Id';
$competitionValue = $competition['value'] ?? 0;
$teamsCompStatsByComp = $this->createQueryBuilder('t')
->select('t.Id, IDENTITY(t.competitionId) competitionId, t.competitionOldId, IDENTITY(t.teamId) teamId, t.teamOldId, SUM(goalsAttempted) goalsAttempted')
->where('t.'.$competitionField.' = ?1')
->groupBy('t.teamId')
->orderBy('t.Id', 'ASC')
->setParameter('1', $competitionValue)
->getQuery()
->getResult()
;
foreach ($teamsCompStatsByComp as $key => $teamCompStats) {
$teamsCompStatsByComp[$key] = new TeamStatistics($teamCompStats);
}
return new ArrayCollection($teamsCompStatsByComp);
}
I think we should open an issue on Github to improve partial syntax behavior.
Related
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
I have 2 Entities
User
Article
and a “likedByUsers” Many To Many relationship between both.
When I show an article, I want to know if the user has liked it so a heart icon is shown.
I've got this in the ArticleRepository:
public function findOneBySlug($slug,$userId): ?Pack
{
return $this->createQueryBuilder('p')
->andWhere('p.slug = :val')
->setParameter('val', $slug)
->addSelect('COUNT(u) AS userLike', 'p')
->leftJoin("p.users", 'u', 'WITH', 'u.id = :userId')
->setParameter('userId', $userId)
->getQuery()
->getOneOrNullResult()
;
}
But it throws an error:
Return value of App\Repository\ArticleRepository::findOneBySlug() must be
an instance of App\Entity\Article or null, array returned
I want to add "userLike" (bool) to the Article returned entity. Anyone can help me out?
calling addSelect(...) on a query builder might change the return type / format.
in your particular case, the former db result was something like [... all the article properties ...] which hydration and the getOneOrNullResult turns into one Article or null.
the new format looks like
[... all the article properties ..., userlike], which hydration turns into [Article, userlike] which can't possibly turned into one Article or a null result, because it's a "more complex" array.
So you have to use a different result fetcher. Depending on what the caller of your function expects as a return value (I would expect an article ^^) you maybe should rename the function or add a virtual property on article to hide the userlike or something, so you can return just the Article or null.
So the solution that I would choose:
$result = $this->createQueryBuilder(...)
//...
->getSingleResult();
if(!$result) {
// empty result, obviously
return $result;
}
// $result[0] is usually the object.
$result[0]->userLike = $result['userLike'];
// or $result[0]->setUserLike($result['userLike'])
return $result[0];
btw: $this->createQueryBuilder($alias) in a repository automatically calls ->select($alias), so you don't have to addSelect('... userLike', 'p') and just do addSelect('... userLike')
An application has a page of statistics representing dozens of calculations. To avoid duplicating code in a repository the error
Error: 'c' is used outside the scope of its declaration
occurs when attempting to insert DQL with conditions into a QueryBuilder.
The basic entities include Household and Contact. Calculations are based on contact date range, site (location of contact), and type (type of contact). There is a service that creates an array of where clauses and query parameters, as will be evident in the code below.
I know the calculation works if all the code occurs in a single function. It seems the problem arises from the join with the Contact entity and its necessary constraints. Can DRY be accomplished in this scenario?
All of the following appear in the Household entity's repository.
The DQL is:
private function reportHousehold($criteria)
{
return $this->createQueryBuilder('i')
->select('i.id')
->join('TruckeeProjectmanaBundle:Contact', 'c', 'WITH',
'c.household = i')
->where($criteria['betweenWhereClause'])
->andWhere($criteria['siteWhereClause'])
->andWhere($criteria['contactWhereClause'])
->getDQL()
;
}
Example of $criteria: $criteria['betweenWhereClause'] = 'c.contactDate BETWEEN :startDate AND :endDate'
One of the calculations on Household:
public function res($criteria)
{
$parameters = array_merge(
$criteria['betweenParameters'], $criteria['siteParameters'],
$criteria['startParameters'], $criteria['startParameters'],
$criteria['contactParameters']);
$qb = $this->getEntityManager()->createQueryBuilder();
return $this->getEntityManager()->createQueryBuilder()
->select('h.id, 12*(YEAR(:startDate) - h.arrivalyear) + (MONTH(:startDate) - h.arrivalmonth) Mos')
->from('TruckeeProjectmanaBundle:Household', 'h')
->distinct()
//DQL inserted here:
->where($qb->expr()->in('h.id', $this->reportHousehold($criteria)))
->andWhere($qb->expr()->isNotNull('h.arrivalyear'))
->andWhere($qb->expr()->isNotNull('h.arrivalmonth'))
->andWhere($criteria['startWhereClause'])
->setParameters($parameters)
->getQuery()->getResult()
;
}
You're either missing getRepository() or from()
Try this (my prefered choice) :
private function reportHousehold($criteria) {
return $this->getEntityManager
->createQueryBuilder()
->select("i.id")
->from(YourEntity::class, "i")
->join("TruckeeProjectmanaBundle:Contact", "c", "WITH", "c.household=i.id")
->where($criteria['betweenWhereClause'])
->andWhere($criteria['siteWhereClause'])
->andWhere($criteria['contactWhereClause'])
->getQuery()
->execute();
}
Or this
private function reportHousehold($criteria) {
return $this->getEntityManager
->getRepository(YourEntity::class)
->createQueryBuilder("i")
->select("i.id")
->join("TruckeeProjectmanaBundle:Contact", "c", "WITH", "c.household=i.id")
->where($criteria['betweenWhereClause'])
->andWhere($criteria['siteWhereClause'])
->andWhere($criteria['contactWhereClause'])
->getQuery()
->execute();
}
Careful, I'm assuming you're on Symfony 3 or above.
If not, replace YourEntity::class by Symfony 2 syntax which is "YourBundle:YourEntity"
In a sense Preciel is correct: the solution does require the use of $this->getEntityManager()->createQueryBuilder(). Instead of injecting DQL as a subquery, the trick is to return an array of ids and use the array in an IN clause. The effect is to remove any consideration of entities other than the Household entity from the calculation. Here's the result:
public function res($criteria)
{
$parameters = array_merge($criteria['startParameters'], $criteria['startParameters'], ['hArray' => $this->reportHousehold($criteria)]);
$qb = $this->getEntityManager()->createQueryBuilder();
return $this->getEntityManager()->createQueryBuilder()
->select('h.id, 12*(YEAR(:startDate) - h.arrivalyear) + (MONTH(:startDate) - h.arrivalmonth) Mos')
->from('TruckeeProjectmanaBundle:Household', 'h')
->distinct()
->where('h.id IN (:hArray)')
->andWhere($qb->expr()->isNotNull('h.arrivalyear'))
->andWhere($qb->expr()->isNotNull('h.arrivalmonth'))
->setParameters($parameters)
->getQuery()->getResult()
;
}
private function reportHousehold($criteria)
{
$parameters = array_merge($criteria['betweenParameters'], $criteria['siteParameters'], $criteria['contactParameters']);
return $this->createQueryBuilder('i')
->select('i.id')
->join('TruckeeProjectmanaBundle:Contact', 'c', 'WITH', 'c.household = i')
->where($criteria['betweenWhereClause'])
->andWhere($criteria['siteWhereClause'])
->andWhere($criteria['contactWhereClause'])
->setParameters($parameters)
->getQuery()->getResult()
;
}
In my symfony project I have two entities that are related via one to many.
I need to find the first and last child, so I use repository functions that look like this:
public function getFirstPost(Topic $topic)
{
$query = $this->createQueryBuilder('t')
->addSelect('p')
->join('t.posts', 'p')
->where('t.id = :topic_id')
->setParameter('topic_id' => $topic->getId())
->orderBy('p.id', 'ASC')
->setMaxResults(1)
->getQuery();
return $query->getOneOrNullResult();
}
public function getLastPost(Topic $topic)
{
$query = $this->createQueryBuilder('t')
->addSelect('p')
->join('t.posts', 'p')
->where('t.id = :topic_id')
->setParameter('topic_id' => $topic->getId())
->orderBy('p.id', 'DESC')
->setMaxResults(1)
->getQuery();
return $query->getOneOrNullResult();
}
So the only difference is in in ->orderBy(), for the first Post I use ASC and for the last I use DESC.
Now If I use one of those functions from my controller, the return the expected result and work just fine. But If I run them both at the same time from my controller, they return the same result, which they shouldn't.
My guess is that Doctrine caches these queries and the results somehow and that's why the return the same so I tried using $query->useResultCache(false) but that didn't do anything.
So my question is, why is this happening and how can I fix it?
Well, it is cache issue indeed, but mostly it is query issue. Instead of returning a post in these function you return the whole topic with joined posts.
What you can do is to rewrite these queries to select Post entity directly and join Topic entity to it which will be filtered by.
If you really(dont do this) need these queries to work you can detach first topic returned by one of those methods and then call the other method:
$this->getDoctrine()->getManager()->detach($firstTopic);
I am able to fetch my data from database by using this structure:
$user = $this->getDoctrine()
->getRepository('AcmeDemoBundle:Emails')
->find(8081);
When I do that, I am able to get my data like this:
$user->getColumnNameHere();
Basically I am able to use Entity Class.
But if I want to use QueryBuilder instead of find I am only getting associative arrays.
$product->createQueryBuilder('p')
->setMaxResults(1)
->where('p.idx = :idx')
->select('p.columnNameHere')
->setParameter('idx', 8081)
->orderBy('p.idx', 'DESC')
->getQuery();
$product = $query->getResult();
$product returnds as array. Is it possible to fetch it withj Entity Managaer Class? If yes, how?
I digg the documentation but it seems not possible or not exist in the doc or I'm just blind :)
Yes you can, usually using:
$repository
->createQueryBuilder('p')
->getQuery()
->execute()
;
This should return you an array of entities.
If you want to get a single entity result, use either getSingleResult or getOneOrNullResult:
$repository
->createQueryBuilder('p')
->getQuery()
->getOneOrNullResult()
;
Warning: These method can potentially throw NonUniqueResultException.
Edit: Ok, so the question was about partial objects: http://docs.doctrine-project.org/en/latest/reference/partial-objects.html
you can get an object instead of array by using "Partial Objects".
here is a tested example with DoctrineORM 2.2.2:
// create query builder
// $em is the EntityManager
$qb = $em->createQueryBuilder();
// specify the fields to fetch (unselected fields will have a null value)
$qb->select ('partial p.{id,pubDate,title,summary}')
->from ('Project\Entity\Post', 'p')
->where ('p.isActive = 1')
->orderBy ('p.pubDate', 'desc');
$q = $qb->getQuery();
$result = $q->getResult();
var_dump($result); // => object
If you wish to return an object from your original query:
$product->createQueryBuilder('p')
->setMaxResults(1)
->where('p.idx = :idx')
->select('p.columnNameHere')
->setParameter('idx', 8081)
->orderBy('p.idx', 'DESC')
->getQuery();
$product = $query->getResult();
Remove this line
->select('p.columnNameHere')
As soon as you use select, it will return an array...
getResult() method returns a collection (an array) of entities. Use getSingleResult() if you're going to fetch only one object.
EDIT:
Oh, I just noticed that you want to fetch a single field of a single object. Use getSingleScalarResult() as #Florian suggests.