Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter @OneToMany in Doctrine

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

like image 615
Iter Ator Avatar asked Mar 17 '17 10:03

Iter Ator


2 Answers

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).

like image 110
LBA Avatar answered Sep 30 '22 01:09

LBA


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

like image 33
Alexandru Cosoi Avatar answered Sep 30 '22 01:09

Alexandru Cosoi