我正在使用Symfony1.4和Doctrine1.2来创建子对象并在执行时打印它们。问题是我总是从第一个查询中获取子对象。
我有以下架构:
Parent:
id
name
Child:
id
parent_id
name
我的操作:
- 最初我有一个父母(id=1),没有孩子
- 我抓住一个父级(id=1)并将该对象存储在
$parent
- 列出它的子对象
- 结果:
none
正常:如预期 - 创建一个新的子项并将其父项设置为
1
- 列出
$parent
的子对象 - 结果:
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
*/