【问题标题】:Get old value before update a record in a form在更新表单中的记录之前获取旧值
【发布时间】:2012-11-10 15:26:54
【问题描述】:

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

怎么了?

【问题讨论】:

    标签: php doctrine symfony-1.4


    【解决方案1】:

    您应该改用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 示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2016-08-18
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多