1

我有一对一关系的简单模式:

Site:
  columns:
    name: { type: string(255) }
User:
  columns:
    name: { type: string(255) }
    site_id: { type: integer }
  relations:
    Site: { foreignType: one }

我正在覆盖 Site::save() 方法(当我从管理生成器编辑站点时调用),我需要对用户进行操作,并且用户再次引用站点:

echo $this->getUser()->getSite()->getName();

当调用 getSite() 时,$this 会被数据库中的值覆盖,因为 Doctrine 从 db 加载“Site”关系并根据身份映射替换 $this。显然,对对象的所有更改都会丢失。在阅读了一些代码后,我发现用户对象在 getUser() 之后没有设置 _references['Site'],这就是 Doctrine 尝试从数据库加载站点的原因。如果我预先

$this->getUser()->setSite($this);

,然后一切都按预期工作,并且不会进行其他查询。另一种解决方法是在查询中加入关系:

$this->site = Doctrine::getTable('Site')
  ->createQuery('s')
  ->leftJoin('s.User u')
  ->leftJoin('u.Site us')
  ->fetchOne();

但这是一种预期的行为吗?我怎样才能让 Doctrine 知道 $this === $this->getUser()->getSite()?我使用 symfony 1.4.18 和 Doctrine 1.2.4。谢谢你。

4

0 回答 0