Doctrine2连接列

问题描述:

我已经在doctrine2中定义了跟随实体(带有symfony)。

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;
}

}

我意识到,如果我拨打$ order-> getPersonId()总是返回一个空值,我必须调用getPerson()-> getId()方法来获取正确的personid。
谁能解释我为什么不填充变量$ personid?
如果定义了联接,我是否应该删除用于联接的列ID?

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?

谢谢

吉赛拉(Gisella)

Gisella

您应该删除 private $ personid; ,这样更好只能在ORM中使用对象。

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

如果使用 $ order-> getPerson()->获得ID,这不是问题; getId(),因为Doctrine不会加载完整的实体。 People 实体只有在您调用除联接键以外的其他字段时才会加载。

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.

您仍然可以拥有这样的getter快捷方式:

You can still have a getter shortcut like this :

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






编辑:
如果您使用Doctrine引用,也可以使用 ID,例如:


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

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

通过这种方式,Doctrine将不会执行 SELECT 查询以加载人员数据。

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