使用Doctrine 1.2,我在从Doctrine_Collection中删除项目时遇到一些问题。
我有一个充满瞬态Doctrine_Records的Doctrine集合。这里$record->delete()
和$record->unlink()
函数似乎无法正常工作,因为它们使用记录的ID。 (哪些瞬态记录没有,因为它们尚未出现在数据库中。)
示例(公司有很多员工)
/* Get a Company that has no Employees yet. */
$company = Doctrine::getTable('Company')->find(1);
/* Add some Employees */
$names = array('Arthur','Bob','Charlie');
foreach ($names as $name)
{
$employee = new Employee;
$employee->name = "Arthur"
$company->Employee->add($employee);
}
现在,在将任何内容保存到数据库之前,我在$emp
中有一名员工,我想从集合中删除。
$emp->delete() /* Does not work when $emp is transient. */
这是什么工作,但我真的怀疑这是要走的路。
foreach($company->Employee as $key => $value)
if ($emp == $value)
{
$company->Employee->remove($key);
break;
}
这不是最简单的方法。有更推荐的方法吗?
答案 0 :(得分:3)
我最终为Doctrine_Collection创建了一个子类,并实现了这个函数,它给了我我想要的行为。
/**
* Looks up a Doctrine_Record in the collection, and - when found - removes it. It is also compatible with serialised records, as
* it tries strict matching (using ===) as well as loose matching (using ==). A strict match precedes a loose match.
*/
public function removeItem($item)
{
if (!($item instanceof Doctrine_Record))
{
throw new Exception("Error while calling removeItem, trying to remove an item that does not descend from Doctrine_Record");
return;
}
foreach ($this as $key=>$value)
{
if ($item === $value)
{
/* Strict match found, remove it and return. */
$this->remove($key);
return;
}
if ($looseMatch === null && $item == $value) $looseMatch = $key;
}
/* No strict match found. If a $matchLoose is on, and aloose match was found, remove it. */
if ($looseMatch !== null)
{
$this->remove($looseMatch);
}
else throw new Exception('No match found trying to remove an item from a collection.');
}