Symfony1.4 和 Doctrine1.2 在执行时间中设置和获取子元素


Symfony1.4 and Doctrine1.2 setting and getting child elements in execution time

我正在使用Symfony1.4和Doctrine1.2来创建子对象并在执行时打印它们。问题是我总是从第一个查询中获取子对象。

我有以下架构:

Parent:
  id
  name
Child:
  id
  parent_id
  name

我的操作:

  1. 最初我有一个父母(id=1),没有孩子
  2. 我抓住一个父级(id=1)并将该对象存储在$parent
  3. 列出它的子对象
  4. 结果:none正常:如预期
  5. 创建一个新的子项并将其父设置为1
  6. 列出 $parent对象
  7. 结果:none 哎呀:我期待 5 岁的新孩子。!

法典:

$parent = Doctrine_Query::create()->from('Parent p')->where('p.id = ?', 1)->limit(1)->fetchOne(); /* from 2. */
print_r($parent->getChild()->toArray()); /* from 3. */
$child = new Child();
$child->setParentId($parent->getId());
$child->save(); /* from 4. */
print_r($parent->getChild()->toArray()); /* from 6. */

我已经尝试在最后一行之前重新抓取$parent,但结果是一样的。

我找到了解决此问题的方法:

$parent = Doctrine_Query::create()->from('Parent p')->where('p.id = ?', 1)->limit(1)->fetchOne();
print_r($parent->getChild()->toArray()); 
$child = new Child();
$child->setParentId($parent->getId());
$child->save(); 
$parent->refresh(true); /* see note! */
print_r($parent->getChild()->toArray()); 

请注意,从Doctrine的评论中:

/**
* refresh
* refresh internal data from the database
*
* @param bool $deep                        If true, fetch also current relations. Caution: this deletes
*                                          any aggregated values you may have queried beforee
*
* @throws Doctrine_Record_Exception        When the refresh operation fails (when the database row
*                                          this record represents does not exist anymore)
* @return boolean
*/