"IN" predicate with Criteria filtering isn't working
Asked Answered
P

1

4

I'm trying to filter a doctrine collection directly with Criteria in order to avoid all collection-loading when I'm searching only for certain elements.

public function bar()
{
    $entity = ...; // not useful for the example
    $property = ...; // not useful for the example but is a getter for a collection
    $ids = [22, 13]; // just for the sake of this example
    $criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));

    return $this->foo($entity, $property, $criteria);
}

public function foo($entity, $property, Criteria $criteria)
{
    return $this->propertyAccessor->getValue($entity, $property)->matching($criteria);
}

Above code will produce this DQL (I'll show only last and relevant part)

AND te.id = ?' with params [22,13]:

And so, this error

Notice: Array to string conversion

I suppose that wrong DQL is generated here, but I don't know why.

Does anyone got a clue?


This is the collection property I'm trying to match on

/**
 * @ORM\ManyToMany(targetEntity="Vendor\Bundle\Entity\Foo")
 * @ORM\JoinTable(name="foo_bar",
 *     joinColumns={@ORM\JoinColumn(name="foo_bar_id", referencedColumnName="id", onDelete="cascade")},
 *     inverseJoinColumns={@ORM\JoinColumn(name="foo_id", referencedColumnName="id")}
 * )
 */
 protected $foo;

Edit

If I try to dump $criteria object, I obtain this

Criteria {#10958 ▼
  -expression: Comparison {#10956 ▼
    -field: "id"
    -op: "IN"
    -value: Value {#10948 ▼
      -value: array:2 [▼
        0 => 22
        1 => 13
      ]
    }
  }
  -orderings: []
  -firstResult: null
  -maxResults: null
}

So this seems to be correct. I'm also aware I could use "or" expressions, but I would prefer to understand why this issue is taking place.

Edit2

I've changed $criteria as follows

$criteria = Criteria::create()
    ->where(Criteria::expr()->eq('id', 22))
    ->orWhere(Criteria::expr()->eq('id', 13));

As now, query is correct but collection isn't: it is empty but shouldn't be (if I run manually that query from mysql cli I obtain what I expect).

So ...

BONUS QUESTION

Can I use Criteria only inside entities getters or repository if I collection isn't already loaded?

Edit3 - Bonus question

It seems that if you don't have collection already loaded, matching criteria is pretty useless. Infact if I loop onto collection elements and call some getters and, then, I use criteria, resulting collection is what I was searching for (but, of course, ALL collection elements are now loaded)

Parlous answered 12/2, 2016 at 9:7 Comment(0)
P
1

I've found this

https://github.com/doctrine/doctrine2/issues/4910

It seems that is a "well-known" issue in ManyToMany collection situations

Parlous answered 12/2, 2016 at 15:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.