简体   繁体   中英

Doctrine ODM Query Builder - Find where collection is empty

I am trying to create a query, using the doctrine ODM query builder, where a referenced association ( eventListeners ) is not empty - or the collection has one or more item.

The query:

$qb = $om->createQueryBuilder(FormService::ENTITY_CLASS_NAME_FORM);
$query = $qb->field('website.$id')->equals(new \MongoId($website->getId()))
            ->field('status.name')->equals(FormService::STATUS_PUBLISHED)
            ->field('eventListeners')->notEqual(array());
            ->getQuery();
$results = $query->execute();

I've been creative in my attempts with the API; This line is clearly incorrect as it still returns all the documents regardless

->field('eventListeners')->notEqual(array());

I can see in the documentation you can use field('eventListeners')->size(3); however I do not know in advance what the collection size should be.

How do you query for non empty collections using Doctrine ODM?

It's probably not the best way to achieve this, but it does work:

$qb = $om->createQueryBuilder(FormService::ENTITY_CLASS_NAME_FORM);
$query = $qb->field('website.$id')->equals(new \MongoId($website->getId()))
            ->field('status.name')->equals(FormService::STATUS_PUBLISHED)
            ->field('eventListeners.0')->exists(true)
            ->getQuery();

$results = $query->execute();

This assumes that it is a 0 based index Collection and not a Hash .

I realise you can do DB.find({eventListeners: {$not: {$size: 0}}}) in mongo, but I'm not sure how to properly structure it in the ODM query builder.

After reviewing the odm documentation I'm not sure if it's even possible to do.

The other approach is to use a $where function: http://docs.mongodb.org/manual/reference/operator/query/where/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM