示例#1
0
文件: Model.php 项目: solve/database
 public function save($forceSave = false)
 {
     if (!$this->isChanged() && !$forceSave) {
         return true;
     }
     $this->_preSave();
     if (!$this->validate()) {
         return false;
     }
     foreach ($this->_dataProcessor->getData() as $columnName => $value) {
         if ($value != $this->_data[$columnName]) {
             $this->_changedData[$columnName] = $value;
         }
     }
     $dataToSave = array();
     foreach ($this->_structure->getColumns() as $column => $info) {
         if (array_key_exists($column, $this->_changedData)) {
             $dataToSave[$column] = $this->_changedData[$column];
         } elseif (array_key_exists('default', $info) && !array_key_exists($column, $this->_data)) {
             $dataToSave[$column] = $info['default'];
         } elseif ($forceSave) {
             if ($column == 'id') {
                 continue;
             }
             $dataToSave[$column] = array_key_exists($column, $this->_data) ? $this->_data[$column] : null;
         }
     }
     $qc = QC::create($this->_tableName);
     $dataToSave = $this->getPackedData($dataToSave);
     if ($this->_isNew) {
         if (empty($dataToSave)) {
             $dataToSave = array($this->_primaryKey => null);
         }
         $this->{$this->_primaryKey} = $qc->insert($dataToSave)->execute();
     } elseif (count($dataToSave)) {
         $qc->update($dataToSave)->where(array($this->_primaryKey => $this->{$this->_primaryKey}))->execute();
     }
     /**
      * Reloading data from DB for the newly created object
      */
     if ($this->_isNew) {
         $data = QC::create($this->_tableName)->where(array($this->_tableName . '.' . $this->_primaryKey => $this->{$this->_primaryKey}))->executeOne();
         $this->setOriginalData($data);
         $this->unpackOriginalData();
     }
     $this->_postSave();
     $this->_isNew = false;
     $this->_changedData = array();
     return true;
 }