doctrine / mongodb-odm

The Official PHP MongoDB ORM/ODM
https://www.doctrine-project.org/projects/doctrine-mongodb-odm/en/latest/
MIT License
1.09k stars 504 forks source link

Query problem with multiple values array #1747

Closed RrOoSsSsOo closed 6 years ago

RrOoSsSsOo commented 6 years ago

I've a problem with multiple value query array

$repository->findBy('FieldName' => array("value1", "value2"));

This aspect is reported into official documentation (par. 7.7.2) but doesn't work. With a single value it's ok $repository->findBy('FieldName' => "value1"));

The only way that works is using "in" operator with array using QueryBuilder

$objects = $repository->createQueryBuilder()
                      ->field('FieldName')->in(array("value1", "value2"))
                      ->getQuery()
                      ->execute();

Components: Database: MongoDB 3.4.5 @ Windows PHP: 7.x with XAMPP @ Windows Framework: Symfony v3.4.4 doctrine/mongodb-odm-bundle v3.4.1 doctrine/mongodb-odm v1.2.1 doctrine/doctrine-bundle v1.8.1 doctrine/mongodb v1.6.1 doctrine/common v2.8.1 alcaeus/mongo-php-adapter v1.1.4

PS: I have the same problem with magic call for field name $repository->findByFieldName("value1"); // Work $repository->findByFieldName(array("value1", "value2")); // Doesn't work

Thanks to all

malarzm commented 6 years ago

This works as designed: you're telling the ODM to look for FieldName which value is array("value1", "value2") - findBy uses $eq and there's no way to change that. If you need $in you must use query builder.

malarzm commented 6 years ago

Also the documentation you're linking to is for ORM, not ODM :)

Steveb-p commented 6 years ago

That's probably the source of confusion. Afaik ORM allows querying by multiple values in it's findBy method.

malarzm commented 6 years ago

IIRC it does, however in Mongo it's perfectly fine to have an array stored in the field thus we can't assume that user wants $in instead of $eq :)

alcaeus commented 6 years ago

PS: I have the same problem with magic call for field name

Regarding magic calls, internally calling findByFieldName('foo') is the same thing as calling findBy(['fieldName' => 'foo']), which explains the similar behavior. Do note that these magic methods are deprecated and will be removed in ODM 2.0.