1

写真とアルバムの2つのテーブルがあります。アルバム テーブルには、そのアルバムの写真の数を含むフィールドがあります。

アルバムを変更して写真を更新するときは、変更を反映するためにアルバム テーブルの写真フィールドの数を更新する必要があります。

    public function updateObject($values=null)
    {        
        $object = parent::updateObject($values);

        if($this->isNew)
        {
         ...
        }
        else
        {
          $old_album = Doctrine_Core::getTable('Photos')
                        ->find($object->getId())->getAlbums();
          if($old_album != $object->getAlbums()
             //update number of photos
        }
    }

しかし、 を削除した場合と同じ$object->getAlbums()値が常に取得され、正しい値が取得されます。$old_album;$old_album$object->getAlbums()

どうしたの?

4

1 に答える 1

0

doUpdateObject()代わりに次のメソッドを使用する必要があります。

protected function doUpdateObject($values)
{
  // this is the album object before the update
  $oldAlbum = clone $this->getObject()->getAlbum();

  // refresh the object with the new values
  parent::doUpdateObject($values);

  // it's an update
  if (!$this->isNew())
  {
    // the old album is removed
    if (!$this->getObject()->get('album_id'))
    {
      // decrease the number of pictures in the old album and save it
      $oldAlbum
        ->setNumberOfPictures($oldAlbum->getNumberOfPictures() - 1)
        ->save();
    }
    elseif ($oldAlbum->get('id') != $this->getObject()->get('album_id'))
    {
      // decrease the number of pictures in the old album and save it
      $oldAlbum
        ->setNumberOfPictures($oldAlbum->getNumberOfPictures() - 1)
        ->save();

      // increase the number of pictures in the current album (save not required)
      $this
        ->getObject()
        ->setNumberOfPictures($this->getObject()->getNumberOfPictures() + 1);
    }
  }
  else
  {
    // increase the number of pictures in the current album (save not required)
    $this
      ->getObject()
      ->setNumberOfPictures($this->getObject()->getNumberOfPictures() + 1);
  }
}

ここには多くのコードの重複があり、アルバムを更新するときに一貫性を保つために常にこれを行う必要があるため、これは最善の方法ではありません。

ロジック全体をモデルに移動する必要があります。より良い解決策はCountCache、ドキュメントのこの例のような動作を使用することです。

于 2012-11-10T16:32:40.730 に答える