I have a @OneToMany
relationship:
/**
* @OneToMany(targetEntity="\MyApp\Entities\Content", mappedBy="clist")
* @OrderBy({"contentOrder"="ASC", "id"="ASC"})
*/
private $contents;
I get all the Content
's, which clist
attribute is the id of the current instance. But the Content
class has an isDeleted
attribute also. If it is set to true, I would like to exclude it from the list.
How is it possible?
I can filter the list in the getContents()
function, but I hope there is a better solution. Maybe somehow in the definition of the @OneToMany
relationship
Option 1
I recommend using Criteria to filter collections
use Doctrine\Common\Collections\Criteria;
$clist = $entityManager->find('Clist', $clistId);
$contentCollection = $clist->getContents();
$criteria = Criteria::create()
->where(Criteria::expr()->eq("isDeleted", false))
;
$undeletedContents = $contentCollection->matching($criteria);
Option 2
Another option could be to use Filters where you can make sure that as long as the filter is active each and every Query is making sure that a 'where' constraint is attached.
This usually makes sense if you have some attributes which are queried most of the time for most of your entities (like e.g. a ClientId or a Deleted attribute).
If you are using ArrayCollection to store your relations then you can do this:
$criteria = Criteria::create()->where(Criteria::expr()->eq("isDeleted", false));
$contents = $yourMainClass->getContents()->matching($criteria);
Hope this helps,
Alexandru Cosoi
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With