I am not sure if what I want to do is possible or not, but I can't find any documentation on it. Hopefully I am just looking in the wrong places.
What I would like to do is load an object that will always load a subset of a related object. some background - I want to keep a history of the contacts that a user deletes, so when a contact is deleted, I set a isDeleted
column in the db to true. I will rarely want to load the deleted contacts, so I will worry about that later. But when I load a user, and then load the contacts (in my case by serializing the whole user
object), all of the contacts are loaded including the deleted ones. So I would like to only load the contacts that have not been deleted yet. This is what I have right now, and I don't know why it is not working.
use Doctrine\Common\Collections\Criteria,
Doctrine\Common\Collections\ArrayCollection;
class User{
/**
* @ORM\OneToMany(targetEntity="Contacts", mappedBy="user", cascade={"persist"}, fetch="EXTRA_LAZY")
* @ORM\JoinColumn(name="contact_id", referencedColumnName="contact_id")
*/
private $contacts;
public function __construct(){
$this->contacts = new ArrayCollection();
}
/**
* Get contacts
*
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getContacts()
{
// This is where I am filtering the contacts
$criteria = Criteria::create()
->where(Criteria::expr()->eq("isDeleted", false));
return $this->contacts->matching($criteria);
}
And then I am loading and serializing a user using the JMS Serializer and FOSRest in my Controller.
public function getUserAction($slug){
$data = $this->getDoctrine()->getRepository('MyCoreBundle:User')->find($slug);
$view = $this->view($data, 200);
return $this->handleView($view);
}
And the result is the following JSON:
{
userId: 7,
creationDate: "2014-07-28T22:05:43+0000",
isActive: true,
username: "myUser",
contacts: [
{
contactId: 23,
firstName: "Jim",
lastName: "Bin",
email: "zzz@zzz.com",
phone: "1231231231",
isDeleted: true
}
]
}
I am not sure why this is still loading the deleted user. If I do the filtering in my controller instead of the Entity class, then the filtering works. But I don't want to have to do that everywhere in my application that a contact may be loaded. If I could get something working in the Entity class, that would be ideal. Has anyone done something similar that could work?
I'm using Symfony 2.3