PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, March 4, 2022

[FIXED] Doctrine QueryBuilder - ManyToMany - NOT IN - how do I filter only entities where relation does not contain ID?

 March 04, 2022     doctrine, symfony     No comments   

Issue

I have an issue with constructing a suitable query:

$queryBuilder
           ->innerJoin(
               sprintf('o.%s', $property), 
               $property, 
               'WITH',
               sprintf('%s.id = :%s', $property, $parameterName)
           )
           ->setParameter($parameterName, $value)
           ->andWhere(sprintf('%s IS NULL', $property));

When I filter with ->andWhere(sprintf('%s IS NOT NULL', $property)), it's all good, I get all four correct entities.

However, on the ->andWhere(sprintf('%s IS NULL', $property)) query, I am getting some entities from the NOT NULL query, because there are other entities in the toMany relationship, which satisfy the IS NULL clause.

Is there any way to make a query exclusive (do not return a result when the IS NULL condition is triggered by ANY of the related entities).

I know this is quite confusing, but here is an example:

You have a party with invitees.

You want to filter all parties that DO NOT have that particular invitee (say, with id 1).

I can't do that when there are other invitees to the party. For example, one party has invitees with ids 1, 2, and 3. This one will get back to me even when it should not.

If it only had one invitee and this invitee was with id 1, all is fine.

I hope that makes sense.

This is the exact same issue as this one (which is pure sql):

Selecting with NOT IN and Many to Many relationship

Also, I am totally aware of the workaround using a subquery, but this is not feasible in my case, as I need it for a low level filter, where it's gonna be a mess, if I start querying other entities.


Solution

use MEMBER OF expression.

LIKE:

->andWhere(sprintf(':%s NOT MEMBER OF o.%s', $id, $toManyRelation))


Answered By - Ravi Damasiya
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing