Search code examples
symfonydoctrine-ormcriteria

Doctrine 2.3 Criteria. Accessing a related Object


I am trying to set up a Criteria according to the Doctrine Docs.

Unfortunately they don't tell you how to access attributes of an related Object. Let me give you an example.

I have an ArrayCollection of Products. Every Product has a Category. I want to filter the ArrayCollection for a Category Name. Now I am trying to set up a Criteria as follows:

$criteria = Criteria::create()
  ->where(Criteria::expr()->eq("category.name", "SomeCategoryName"));

Now I get the following Exception:

An exception has been thrown during the rendering of a template ("Unrecognized field: category.name")

How can I access a related Object?


Solution

  • I looked into the source code Criteria::expr()->eq("name", --- second value ---). Second value expects an instance of Doctrine\Common\Collections\Expr\Value. So it's not possible to put another Expr or criteria in there. Only the Expr And and Or take another Expr. I'm pretty sure you are suppose to solve this with other functions like filter() or get an iterator with getIterator(). This is how it can be done with the filter() method.

    $filteredProducts = 
        $products->filter(function($key, $element) use ($categoryName) {
            return $element->getCategory()->getName() === categoryName;
        });
    

    If you can an Iterator for each next relation you can nest foreach loops and filter inside those.