user1863635
user1863635

Reputation: 899

How to get associations in Doctrine entity?

I hope it's possible in Doctrine2. I know Propel does that automatically. What I want to do is this:

I have two tables:

workflow (id, name)
inbox (id, workflow_id, name)

And two entities:

Workflow and Inbox

In my Inbox entity I, of course, have this (to relate two tables):

  /**
   * @ORM\ManyToOne(targetEntity="Workflow")
   * @ORM\JoinColumn(nullable=false)
   */
  protected $workflow;

Everything works great. However, I want to be able to get inboxes from the Workflow entity that are associated with that workflow. I can't find how to do it.

Propel does that very simple, you would just do something like this:

$workflow = WorkflowQuery::create()
  ->filterById(1)
  ->findOne(1);

$inboxes = $workflow->getInboxs() 
//Propel just addes 's' to methods that return associations

How, similar this can be done in Doctrine2? Something like this:

$workflow = $this->getRepository('MyBundle:Workflow')->findById(1);
$inboxes = $workflow->getInboxes();

So, is there a way to do this? Thank you.

Upvotes: 1

Views: 831

Answers (1)

Zeljko
Zeljko

Reputation: 5158

Change in controller:

$workflow = $this->getDoctrine()->getRepository('MyBundle:Workflow')->find(1);
$inboxes = $workflow->getInboxes();

Don't forget that you need

// Workflow entity
public function __construct()
{
    // make `use` statement for this, not long
    $this->inboxes = new \Doctrine\Common\Collections\ArrayCollection() ;
}

and

/**
* @ORM\OneToMany(targetEntity="Inbox", mappedBy="workflow", cascade={"persist"})
*/
protected $inboxes ;
public function getInboxes() { return $this->inboxes ; }
// setInboxes(), addInbox(), removeInbox() here

Upvotes: 2

Related Questions