Assume there’s a very basic structure: A Category can contain multiple items of Product:
/**
* @ORM\OneToMany(targetEntity="Product", mappedBy="category", cascade="remove")
*/
protected $products;
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="products")
* @ORM\JoinColumn(name="product_id", referencedColumnName="id")
*/
protected $category;
I get all products, when I access them through the category like this:
$category->products;
Let’s say a Product has an attribute invisible. How can I force Doctrine to only load the products that are visible. Where do I put this query? Into the repository? But than: How Do I call it or switch between “load all” and “load certain”? I could of course request the products separately, but this seems not like a good solution.
The easiest way is to simple add a visibility parameter to your category->getProducts() method:
This does not prevent the loading of all products but it does give you an easy way to decide which products you want. And it’s very easy to implement. You can refine it later.
A second approach would be to create a query to load all your categories with the products. That will avoid the lazy loading of products and allow you to specify exactly which products you want.
And finally, you could follow @w1cked’s suggestion and make a D2 filter. Takes a little bit of effort to understand the process.