bronzett
bronzett

Reputation: 25

Doctrine2 join column

I have defined the follow entity in doctrine2 (with symfony).

/**
 * 
 * @ORM\Table(name="order")
 * @ORM\Entity
 */
class Order

 /**
 * @var integer
 *
 * @ORM\Column(name="personid", type="integer", nullable=false)
 */
private $personid;

 /**
 * @ORM\OneToOne(targetEntity="People")
 * @ORM\JoinColumn(name="personid", referencedColumnName="personid")
 */
private $person;


public function getPersonId()
{
    return $this->personid;
}
public function getPerson()
{
    return $this->person;
}

}

I realize that if I call $order->getPersonId() it return always an empty value and I have to call the getPerson()->getId() method to get the correct personid. Could anyone explain me why the variable $personid is not filled? Should I to delete the column id used for the join if I defined one?

Thanks

Gisella

Upvotes: 0

Views: 542

Answers (2)

Raphaël Malié
Raphaël Malié

Reputation: 4012

You should remove private $personid;, it's better to work with objects only in an ORM.

It's not a problem if you get the ID with $order->getPerson()->getId(), because Doctrine won't load the complete entity. The People entity will only be loaded if you call an other field than the join key.

You can still have a getter shortcut like this :

public function getPersonId()
{
    return $this->getPerson()->getId();
}

Edit : You can also still work with "ID" if you use Doctrine references, like this :

$order->setPerson($em->getReference('YourBundle:People', $personId));

With this way, Doctrine won't perform a SELECT query to load data of the person.

Upvotes: 3

Elyass
Elyass

Reputation: 736

You don't need to have the $personid field when you already have the $person field. $people contains the People object (with all People's attributes including the id).

Moreover, when doctrine translate your object into sql tables, he knows that he have to join with th id so it will create a field (in database) named personid. (It's the name that you defined in your ORM)

  /**
 * @ORM\OneToOne(targetEntity="People")
 * @ORM\JoinColumn(name="personid", referencedColumnName="personid")
 */
private $person;

Sorry for bad english :p

Upvotes: 0

Related Questions