2

How do you create a where condition in Doctrine ODM to find only documents where two fields are equal?

A document exists with two int fields alpha and beta, I want to select all documents where these two fields are equal.

I've tried the following but it returns no results:

    $qb = $this->createQueryBuilder();
    $qb
        ->field('alpha')->in($alphaIds)
        ->where('this.alpha === this.beta')
        ->sort('id', 'DESC');
    return $qb->getQuery()->execute();        

This questions shows how to do it outside of Doctrine where alpha and beta are not equal https://stackoverflow.com/a/8433182/1283381

Community
  • 1
  • 1
lookbadgers
  • 988
  • 9
  • 31

2 Answers2

0

Use the Query Expressions in Doctrine\MongoDB\Query\Expr class to create the where() expression via the expr() method as follows:

$qb = $this->createQueryBuilder();
$qb->addAnd(
    $qb->expr()     
       ->field('alpha')->in($alphaIds)
       ->where('this.alpha === this.beta')
    )
    ->sort('id', 'DESC');
return $qb->getQuery()->execute();
chridam
  • 100,957
  • 23
  • 236
  • 235
  • That results in the execution without any conditions i.e. `db.DocumentName.find();` – lookbadgers May 18 '16 at 14:10
  • I was just showing the salient parts, you can then return the query execution as you did `return $qb->getQuery()->execute();` – chridam May 18 '16 at 14:11
  • Yes, I still included `$qb->getQuery()->execute();` in the code. – lookbadgers May 18 '16 at 14:13
  • It's created a condition but no results found `db.DocumentName.find({ "$and": [ { "alpha": { "$in": [ 2, 17, 3 ] }, "$where": "this.alpha === this.beta" } ] }).sort({ "_id": -1 });` I've checked document and records exist where alpha and beta = (int) 3 – lookbadgers May 18 '16 at 14:33
0

If someone will be looking for an answer now:

$qb = $this->createQueryBuilder('a');
$qb
   ->andWhere($qb->expr()->in('a.alfa', $alphaIds))
   ->andWhere($qb->expr()->eq('a.alpha','a.beta'))
   ->orderBy('id', 'DESC');
return $qb->getQuery()->getResult();
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jul 22 '23 at 15:19