在更新表单中的记录之前获取旧值

时间:2012-11-10 15:26:54

标签: php doctrine symfony-1.4

我有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()会获得正确的值。

怎么了?

1 个答案:

答案 0 :(得分: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行为,例如文档中的this示例。