John Davidson

php - [SQL/DQL]How to Filter with a IN acting as 'and' and not 'or'

0 comments
Message:


It's hard to describe what I'm trying to do but I 'll do my my best.


I want to filter an Association and I use EntityFilter for that, this association can have multiple value :


For my example, I'm looking for a person who is illustrateur/dessinateur and Animateur/intervenant.


In my index Crud I have 3 persons, one with no activities, one with both activities illustrateur/dessinateurandAnimateur/intervenantand on with only one activityAnimateur/intervenant`.



Now if I filter with both activities, 2 peoples are showing and it's not the behavior I want :



I only want Farrah because it's the only one who's got the 2 activities.


Then I looked in EntityFilter and I have notices they use the class orX :


if ($entityDto->isToManyAssociation($property)) {
// the 'ea_' prefix is needed to avoid errors when using reserved words as assocAlias ('order', 'group', etc.)
// see https://github.com/EasyCorp/EasyAdminBundle/pull/4344
$assocAlias = 'ea_'.$filterDataDto->getParameterName();
$queryBuilder->leftJoin(sprintf('%s.%s', $alias, $property), $assocAlias);

if (0 === \count($value)) {
$queryBuilder->andWhere(sprintf('%s %s', $assocAlias, $comparison));
} else {
$orX = new Orx();
$orX->add(sprintf('%s %s (:%s)', $assocAlias, $comparison, $parameterName));
if ('NOT IN' === $comparison) {
$orX->add(sprintf('%s IS NULL', $assocAlias));
}
$queryBuilder->andWhere($orX)
->setParameter($parameterName, $this->processParameterValue($queryBuilder, $value));
}

Then I overided this filter and replaced Orx by AndX but still the same result :(


And then I tried this :


foreach ($value as $item) {
if ($comparison === 'NOT IN') {
$queryBuilder->andWhere($queryBuilder->expr()->notIn($assocAlias, [$item->getId()]));
} else {
$queryBuilder->andWhere($queryBuilder->expr()->in($assocAlias, [$item->getId()]));
}
}

But IN act as the OR and I would like a strict if. Is there a way to solve this ?



My Answer:
To filter with an IN clause in SQL/DQL, you can use the following syntax:

sql
SELECT column1, column2
FROM table_name
WHERE column_name IN (value1, value2, value3);


For example, if you have a table called `users` and you want to filter the results based on a list of user IDs, you can use the following query:

sql
SELECT id, name
FROM users
WHERE id IN (1, 2, 3);


This query will return the `id` and `name` columns for users whose `id` is either 1, 2, or 3.

Rate this post

3 of 5 based on 8744 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us