2012-01-24 11 views
0

Doctrine 1.2を使用して、Doctrine_Collectionからアイテムを削除する際に問題が発生しています。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に1人の従業員がいます。これはコレクションから削除したいものです。

$emp->delete() /* Does not work when $emp is transient. */ 

これはうまくいくのですが、実際にはそれがどうなるのか疑問です。

foreach($company->Employee as $key => $value) 
    if ($emp == $value) 
    { 
     $company->Employee->remove($key); 
     break; 
    } 

これは最も簡単な方法です。これを行うための推奨方法はありますか?

答えて

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.'); 

    } 
関連する問題