I got two tables with an ManyToOne Relationship (Many "Entity1" to One "Entity2").
Now I need to get the first and the last Entity from Entity1 which belongs to Entity2. The amounts of "Entity1" for a "Entity2" will be counted in the "entity1_in_entity2_id" Column.
Also there is a entity2_id Column in Entity1 to indentify Entity2.
I know I could achieve this with an nativeQuery with Subselects and I already did this, but now I want to do this with the QueryBuilder but I don't know how. I want to try MAX() and MIN() to get the last and first one.
The var $id is set by the function which calls the function this snippet is from.
I tried some coding by myself, this I what I got so far:
$qb = $this->createQueryBuilder('e');
$qb->select()
->where('e.entity2_id = ' . $id)
->orwhere($qb->expr()->orX(
$qb->expr()->min('e.entity1_in_entity2_id'),
$qb->expr()->max('e.entity1_in_entity2_id')
));
return $qb->getQuery()->getResult();
By now I get the following error
[Syntax Error] line 0, col 114: Error: Expected =, <, <=, <>, >, >=, !=, got 'OR'
And don't worry about the names, I must use dummy data sadly, would be easier to explain if use the real table names :D
Based on doctrine documentation: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/query-builder.html#the-expr-class
It should be something like:
->add('where', $qb->expr()->orX(
$qb->expr()->eq('u.id', $qb->expr()->eq('e.entity1_in_entity2_id', $qb->expr()->min('e.entity1_in_entity2_id')),
$qb->expr()->eq('u.id', $qb->expr()->eq('e.entity1_in_entity2_id', $qb->expr()->max('e.entity1_in_entity2_id'))
))
if you really want to use expr, you can also just use
->addSelect('MAX(e.entity1_in_entity2_id) as maxid,MIN(e.entity1_in_entity2_id) as minid')
->having('e.entity1_in_entity2_id IN(minid,maxid)
or
->having('e.entity1_in_entity2_id = minid OR e.entity1_in_entity2_id = maxid')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.