save the entity

@access public
@param  bool $bOnDuplicateKeyUpdate (to do insert on duplicate key)
@return object
962373
public function save($bOnDuplicateKeyUpdate = false)
    {
        /**
         * Trigger on an entity to initialize it before the save
         */
        if (method_exists(get_called_class(), 'beforeSave')) { static::beforeSave(); }

        $mPrimaryKeyName = $this->_mPrimaryKeyName;

        if ($bOnDuplicateKeyUpdate === false) { $bInsertMode = false; }
        else { $bInsertMode = true; }

        if ($mPrimaryKeyName === false) {

            throw new \Exception('['.__FILE__.' (l.'.__LINE__.'] no primary key on this table!');
        }
        else if (is_string($mPrimaryKeyName)) {

            $sMethodPrimaryKey = 'get_'.$this->_mPrimaryKeyNameWithoutMapping;
            $aPrimaryKey = array($mPrimaryKeyName => $this->$sMethodPrimaryKey());

            if ($this->$sMethodPrimaryKey() < 1) { $bInsertMode = true; }
        }
        else {

            $aPrimaryKey = array();

            $oOrm = new Orm;

            $iResults = $oOrm->select(array('*'))
                ->from(preg_replace('/^.*\\\\([a-zA-Z0-9_]+)$/', '$1', get_called_class()));

            $oWhere = new Where;

            foreach($mPrimaryKeyName as $sKey => $sPrimaryKey) {

                $sMethodPrimaryKey = 'get_'.$this->_mPrimaryKeyNameWithoutMapping[$sKey];
                $aPrimaryKey[$sPrimaryKey] = $this->$sMethodPrimaryKey();


                $oWhere->andWhereEqual($sPrimaryKey, $aPrimaryKey[$sPrimaryKey]);
            }

            $aResults = $oOrm->where($oWhere)
                ->load();

            if (count($aResults) < 1) { $bInsertMode = true; }
        }

        $aEntityTmp = get_object_vars(LibEntity::getRealEntity($this));
        $aEntity = array();

        foreach ($aEntityTmp as $sKey => $mField) {

            if ($mField !== null && !is_object($mField)) {

                $aEntity[$sKey] = $mField;
            }
        }

        /**
         * check if the virtual foreign key in this model is respected
         */
        if (count($this->_aForeignKey) > 0) {

            foreach ($this->_aForeignKey as $sName => $aForeignKey) {

                if ($aForeignKey['has_one'] == 1) {

                    $sMethodPrimaryKey = 'get_'.$aForeignKey['foreign_key'];
                    $mFIeld = $this->$sMethodPrimaryKey();

                    if ($mFIeld) {

                        $oOrm = new Orm;

                        $iResults = $oOrm->select(array('*'))
                            ->from($aForeignKey['entity_join_name']);

                        $oWhere = new Where;

                        $oWhere->whereEqual($aForeignKey['primary_key_name'], $mFIeld);

                        $aResults = $oOrm->where($oWhere)
                            ->load();

                        if (count($aResults) < 1) {

                            if ($aForeignKey['foreign_key_options']['message']) {

                                throw new \Exception($aForeignKey['foreign_key_options']['message']);
                            }
                            else {

                                throw new \Exception('Foreign Key not respected!');
                            }
                        }
                    }
                }
            }
        }

        /**
         * check if the virtual foreign key in the others models are respected
         */
        $oReflectionClass  = new \ReflectionClass(get_called_class());
        $oReflectionProperties = $oReflectionClass->getProperties();

        foreach($oReflectionProperties as $mKey => $aOne) {

            $sCommentPhpDoc = $aOne->getDocComment();

            if (strstr($sCommentPhpDoc, '@OneToMany')) {

                $sClassName = $aOne->class;
                $oClass = new $sClassName;

                if (count($oClass->getForeignKey()) > 0) {

                    foreach ($oClass->getForeignKey() as $sName => $aForeignKey) {

                        if ($aForeignKey['has_many'] == 1) {

                            $sMethodPrimaryKey = 'get_'.$aForeignKey['foreign_key'];
                            $mFIeld = $this->$sMethodPrimaryKey();

                            if ($mFIeld) {

                                $oOrm = new Orm;

                                $iResults = $oOrm->select(array('*'))
                                    ->from($aForeignKey['entity_join_name']);

                                $oWhere = new Where;

                                $oWhere->whereEqual($aForeignKey['primary_key_name'], $mFIeld);

                                $aResults = $oOrm->where($oWhere)
                                    ->load();

                                if (count($aResults) < 1) {

                                    if ($aForeignKey['foreign_key_options']['message']) {

                                        throw new \Exception($aForeignKey['foreign_key_options']['message']);
                                    }
                                    else {

                                        throw new \Exception('Foreign Key not respected!');
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        $oOrm = new Orm;

        if ($bInsertMode === true) {

            $oOrm->insert(preg_replace('/^.*\\\\([a-zA-Z0-9_]+)$/', '$1', get_called_class()))
                ->values($aEntity);

            if ($bOnDuplicateKeyUpdate === true) {

                $oOrm->onDuplicateKeyUpdate($aEntity);
            }

            $iResults = $oOrm->save();
        }
        else {

            $iResults = $oOrm->update(preg_replace('/^.*\\\\([a-zA-Z0-9_]+)$/', '$1', get_called_class()))
                ->set($aEntity)
                ->where($aPrimaryKey)
                ->save();
        }

        if (is_string(LibEntity::getPrimaryKeyName($this))) {
            $methodName = 'set_'.LibEntity::getPrimaryKeyName($this);
            $this->$methodName($iResults);
        }

        return $iResults;
    }
1301068
public function save($force=false)
    {
        if (!self::$_loaded) {
            self::_loadColumns();
        }

        // check for callbacks before validation below
        $calling = get_called_class();
        if (!self::_checkCallback($calling, "before_save", $this)) {
            return false;
        }

        // with all the before callbacks checked, check if its valid
        if (!$this->isValid()) {
            return false;
        }

        $pk         = $calling::isIgnoringCase() ? strtolower($calling::getPK()) : $calling::getPK();
        $pk_value   = array_key_exists($pk, $this->_data) ? $this->_data[$pk] : null;
        $attrs      = $this->_data;

        if (!$pk_value) {
            // if there is a method to get the new primary key value on the class, 
            // call it
            if (method_exists($calling, "getNewPKValue")) {
                $pk_value = $calling::getNewPKValue();
                if (!$this->_data[$pk]) {
                    $this->_data[$pk] = $pk_value;
                }
                $attrs = $this->_data;
            }
        }

        // if found a primary key value, check if exists
        if ($pk_value) {
            $this->_new_rec = !self::find($pk_value);
        }

        $rst    = false;
        $newr   = false;

        if ($this->_new_rec) {
            $newr = true;
            self::_checkCallback($calling, "before_create", $this);
            $rst = $this->_insert($attrs, $calling, $pk, $pk_value);
        } else {
            self::_checkCallback($calling, "before_update", $this);

            // no need to update if there weren't changes
            if (sizeof($this->changed()) < 1 && !$force) {
                Log::log("No changes, not updating");
                $rst = true;
            } else {
                $rst = $this->_update($attrs, $calling, $pk, $pk_value);
            }
        }

        if ($rst) {
            self::_checkCallback($calling, "after_save", $this);
            if ($newr) {
                self::_checkCallback($calling, "after_create", $this);
            } else {
                self::_checkCallback($calling, "after_update", $this);
            }
        }
        $this->_prev_data = $this->_data;
        return $rst;
    }
1254366
public function save()
    {
        if (!is_array($this->_aFieldNames)) {
            return false;
        }

        // #739A - should be executed here because of date/time formatting feature
        if ($this->isAdmin() && !\OxidEsales\Eshop\Core\Registry::getConfig()->getConfigParam('blSkipFormatConversion')) {
            foreach ($this->_aFieldNames as $name => $value) {
                $longName = $this->_getFieldLongName($name);
                if (isset($this->$longName->fldtype) && $this->$longName->fldtype == 'datetime') {
                    \OxidEsales\Eshop\Core\Registry::getUtilsDate()->convertDBDateTime($this->$longName, true);
                } elseif (isset($this->$longName->fldtype) && $this->$longName->fldtype == 'timestamp') {
                    \OxidEsales\Eshop\Core\Registry::getUtilsDate()->convertDBTimestamp($this->$longName, true);
                } elseif (isset($this->$longName->fldtype) && $this->$longName->fldtype == 'date') {
                    \OxidEsales\Eshop\Core\Registry::getUtilsDate()->convertDBDate($this->$longName, true);
                }
            }
        }

        $return = false;

        $action = null;
        $response = null;
        /** We must check on the master database, if an entry exists, so we switch to master connection.*/
        \OxidEsales\Eshop\Core\DatabaseProvider::getMaster();
        if ($this->exists()) {
            //only update if derived update is allowed
            if ($this->allowDerivedUpdate()) {
                $response = $this->_update();
                $action = ACTION_UPDATE;
            }
        } else {
            $response = $this->_insert();
            $action = ACTION_INSERT;
            $this->dispatchEvent(new AfterModelInsertEvent($this));
        }

        $this->onChange($action);

        if ($response) {
            $return = $this->getId();
        }

        return $return;
    }
805659
public function save($featureData, $autoUpdate = true)
    {
        if (!is_array($featureData) && !is_object($featureData)) {
            throw new \Exception("Feature data given isn't compatible to save into the table: " . $this->getTableName());
        }

        $feature = $this->create($featureData);
        $event   = array(
            'item'    => &$featureData,
            'feature' => $feature
        );

        $this->allowSave = true;

        if (isset($this->events[ static::EVENT_ON_BEFORE_SAVE ])) {
            $this->secureEval($this->events[ static::EVENT_ON_BEFORE_SAVE ], $event);
        }

        if ($this->allowSave) {
            // Insert if no ID given
            if (!$autoUpdate || !$feature->hasId()) {
                $feature = $this->insert($feature);
            } // Replace if has ID
            else {
                $feature = $this->update($feature);
            }
        }

        if (isset($this->events[ static::EVENT_ON_AFTER_SAVE ])) {
            $this->secureEval($this->events[ static::EVENT_ON_AFTER_SAVE ], $event);
        }

        // Get complete feature data
        $result = $this->getById($feature->getId(), $feature->getSrid());

        return $result;
    }
1133975
public function save($obj, $where = [], $isUpdate = false)
    {
        $obj    = $this->convertToDB($obj);
        $PK     = $this->getPK();
        $params = [];

        if (!empty($where)) {
            $i                  = 0;
            $paramsForSqlString = '';

            foreach ($this->fields as $field) {
                if ($field->noUpdate() || !isset($obj->{$field->identifier()}))
                    continue;

                $params[':' . $field->identifier()] = $obj->{$field->identifier()};

                if ($i>0) {
                    $paramsForSqlString .= ', ' . $field->identifier() . '=:' . $field->identifier();
                } else {
                    $paramsForSqlString .= $field->identifier() . '=:' . $field->identifier();
                }

                $i++;
            }

            //where attributes
            $j = 0;

            foreach ($where as $key => $value) {
                if ($j>0) {
                    $whereString = ' AND ' . $key . '=:' . $key;
                } else {
                    $whereString = ' WHERE ' . $key . '=:' . $key;
                }

                $params[':' . $key] = $value;
            }

            $sql = 'UPDATE ' . $this->table() . ' SET ' . $paramsForSqlString . $whereString;

            if ($this->isQueryDumpEnabled()) {
                var_dump($sql);
            }

            $this->setQuery($sql);
            $this->setParams($params);

            GapOrm::getDriver()->query($sql, $params);
            $query = GapOrm::getDriver()->update();

            if ($query) {
                return $query;
            }

            return false;
        }

        if ((property_exists($obj, $PK->identifier()) && $PK->noInsert()) || $isUpdate) {
            //Update
            $i                  = 0;
            $paramsForSqlString = '';

            foreach ($this->fields as $field) {
                if ($field->noUpdate() || !isset($obj->{$field->identifier()})) {
                    continue;
                }

                $params[':' . $field->identifier()] = $obj->{$field->identifier()};

                if ($i>0) {
                    $paramsForSqlString .= ', ' . $field->identifier() . '=:' . $field->identifier();
                } else {
                    $paramsForSqlString .= $field->identifier() . '=:' . $field->identifier();
                }

                $i++;
            }

            $params[':' . $PK->identifier()] = $obj->{$PK->identifier()};

            $sql = 'UPDATE ' . $this->table() . ' SET ' . $paramsForSqlString . ' WHERE '. $PK->identifier() .'=:'. $PK->identifier();

            if ($this->isQueryDumpEnabled()) {
                var_dump($sql);
            }

            $this->setQuery($sql);
            $this->setParams($params);

            GapOrm::getDriver()->query($sql, $params);
            $query = GapOrm::getDriver()->update();

            if ($query) {
                return $query;
            }

            return false;
        } else {
            //Insert
            $i                  = 0;
            $paramsForSqlString = '(';
            $valueForSqlString  = '(';

            foreach ($this->fields as $field) {
                if ($field->noInsert() || !isset($obj->{$field->identifier()})) {
                    continue;
                }

                $params[':' . $field->identifier()] = $obj->{$field->identifier()};

                if ($i>0) {
                    $paramsForSqlString .= ', ' . $field->identifier();
                    $valueForSqlString  .= ', :' . $field->identifier();
                } else {
                    $paramsForSqlString .= $field->identifier();
                    $valueForSqlString  .= ':' . $field->identifier();
                }

                $i++;
            }

            $paramsForSqlString .= ')';
            $valueForSqlString  .= ')';
            $sql                 = 'INSERT INTO ' . $this->table() . ' ' . $paramsForSqlString . ' VALUES ' . $valueForSqlString;

            if ($this->isQueryDumpEnabled()) {
                var_dump($sql);
            }

            $this->setQuery($sql);
            $this->setParams($params);

            GapOrm::getDriver()->query($sql, $params);
            $query = GapOrm::getDriver()->insert();

            if ($query) {
                return $query;
            }

            return false;
        }
    }
529574
public function save()
    {
        if (!empty($this->ltiResultSourcedId) && !is_null($this->resourceLink)) {
            $ok = $this->resourceLink->getConsumer()->getStorage()->userSave($this);
        } else {
            $ok = true;
        }

        return $ok;
    }
654443
public function save(): bool
	{
		$success = true;

		if(!$this->isPersisted)
		{
			// This is a new record so we need to insert it into the database.

			$this->insertRecord($this->builder());

			$this->isPersisted = true;
		}
		elseif($this->isModified())
		{
			// This record exists and is modified so all we have to do is update it.

			$success = $this->updateRecord($this->builder());
		}

		if($success)
		{
			// Sync up if save was successful

			$this->synchronize();
		}

		return $success;
	}
88376
public function save() {

		if (empty(static::$table))
			$table = strtolower(substr(static::table(), strpos(static::table(), '\\')+1));
		else
			$table = static::$table;

		if (isset($this->_data[$table]) && count($this->_data[$table]) <= 0 ) {
			$post = $_POST;
			while(list($field, $value) = each($post)) {
				// Next if is Primary Keys
				// if (!empty($this->_id) && array_key_exists($field, $this->_id))
					// continue;
				
				$this->_data[$table][$field] = addslashes($value);
				$this->$field = $value;
			}
		}

		if ($table != '') {
			// Untuk menambah record
			if ($this->add == TRUE) {
				$before = $this->before();
				if (is_array($before) && count($before) > 1) {
					if (isset($before['insert'])) {
						$insert = $before['insert'];
						while(list($field, $value) = each($insert))
							$this->_data[$table][$field] = $value;
					}
				}
				$ret = self::$db->$table->insert($this->_data[$table]);
				$after = $this->after();
				if (is_array($after) && count($after) > 1) {
					if (isset($after['insert']) && is_callable($after['insert'])) {
						$insert = $after['insert'];
						$insert($this->_data[$table]);
					}
				}
			}
			// Untuk mengupdate record
			else {
				$before = $this->before();
				if (is_array($before) && count($before) > 1) {
					if (isset($before['update'])) {
						$update = $before['update'];
						while(list($field, $value) = each($update))
							$this->_data[$table][$field] = $value;
					}
				}
				$ret = self::$db->$table->update($this->_id, $this->_data[$table]);
				$after = $this->after();
				if (is_array($after) && count($after) > 1) {
					if (isset($after['update']) && is_callable($after['update'])) {
						$update = $after['update'];
						$update(array('pk'=>$this->_id, 'data'=>$this->_data[$table]));
					}
				}
			}
			
			$this->_data[$table] = array();
		}

		
		return $ret;
	}
616262
public function save()
	{
		// Validate
		if (!$this->validate())
		{
			return false;
		}

		// Handle cases where the primary key might be an empty string
		// For auto-increment in strict-mode DBs, this needs to be NULL
		// instead.
		if ($this->hasAttribute($this->getPrimaryKey())
		 && !$this->get($this->getPrimaryKey()))
		{
			$this->set($this->getPrimaryKey(), null);
		}

		// See if we're creating or updating
		$method = $this->isNew() ? 'create' : 'modify';
		$result = $this->$method();

		// Only perform the following upon success
		if ($result)
		{
			// Purge cache
			$this->purgeCache();

			// If creating, result is our new id, so set that back on the model
			if ($this->isNew())
			{
				$this->set($this->getPrimaryKey(), $result);
				\Event::trigger($this->getTableName() . '_new', ['model' => $this]);
			}

			\Event::trigger('system.onContentSave', array($this->getTableName(), $this));
		}

		return $result;
	}
968545
public function save($cascade = null, $use_transaction = false)
	{
		// Load temporal properties.
		$timestamp_start_name = static::temporal_property('start_column');
		$timestamp_end_name = static::temporal_property('end_column');
		$mysql_timestamp = static::temporal_property('mysql_timestamp');

		$max_timestamp = static::temporal_property('max_timestamp');
		$current_timestamp = $mysql_timestamp ?
			\Date::forge()->format('mysql') :
			\Date::forge()->get_timestamp();

		// If this is new then just call the parent and let everything happen as normal
		if ($this->is_new())
		{
			static::disable_primary_key_check();
			$this->{$timestamp_start_name} = $current_timestamp;
			$this->{$timestamp_end_name} = $max_timestamp;
			static::enable_primary_key_check();

			// Make sure save will populate the PK
			static::enable_id_only_primary_key();
			$result = parent::save($cascade, $use_transaction);
			static::disable_id_only_primary_key();

			return $result;
		}
		// If this is an update then set a new PK, save and then insert a new row
		else
		{
			// run the before save observers before checking the diff
			$this->observe('before_save');

			// then disable it so it doesn't get executed by parent::save()
			$this->disable_event('before_save');

			$diff = $this->get_diff();

			if (count($diff[0]) > 0)
			{
				// Take a copy of this model
				$revision = clone $this;

				// Give that new model an end time of the current time after resetting back to the old data
				$revision->set($this->_original);

				self::disable_primary_key_check();
				$revision->{$timestamp_end_name} = $current_timestamp;
				self::enable_primary_key_check();

				// Make sure relations stay the same
				$revision->_original_relations = $this->_data_relations;

				// save that, now we have our archive
				self::enable_id_only_primary_key();
				$revision_result = $revision->overwrite(false, $use_transaction);
				self::disable_id_only_primary_key();

				if ( ! $revision_result)
				{
					// If the revision did not save then stop the process so the user can do something.
					return false;
				}

				// Now that the old data is saved update the current object so its end timestamp is now
				self::disable_primary_key_check();
				$this->{$timestamp_start_name} = $current_timestamp;
				self::enable_primary_key_check();

				$result = parent::save($cascade, $use_transaction);
			}
			else
			{
				// If nothing has changed call parent::save() to insure relations are saved too
				$result = parent::save($cascade, $use_transaction);
			}

			// make sure the before save event is enabled again
			$this->enable_event('before_save');

			return $result;
		}
	}
1258581
public function save($data = null)
    {

        //1. Check if we have data and deal with it!
        if (!is_null($data)) {
            if (!$this->bindData($data)) {
                //we could not save the data
                return false;
            }
        }
        //2. Check if the primary key has a value
        $primary = $this->keys();

        //3. if the primary key has a value, then we are updating, else we are inserting
        if (isset($primary->Value) && !empty($primary->Value)) {
            return $this->update($primary->Value);
        } else {
            return $this->insert();
        }
        //if we get here then there is a problem
        return false;
    }
997129
public function save($item, $autoUpdate = true)
    {
        $result = null;
        $this->allowSave = true;
        if (isset($this->events[ self::EVENT_ON_BEFORE_SAVE ])) {
            $this->secureEval($this->events[ self::EVENT_ON_BEFORE_SAVE ], array(
                'item' => &$item
            ));
        }
        if ($this->allowSave) {
            $result = $this->getDriver()->save($item, $autoUpdate);
        }

        if (isset($this->events[ self::EVENT_ON_AFTER_SAVE ])) {
            $this->secureEval($this->events[ self::EVENT_ON_AFTER_SAVE ], array(
                'item' => &$item
            ));
        }
        return $result;
    }
951912
public function save($updateIndex = false)
    {
        $this->clearCacheTableIndex();
        if ($this->exists()) {
            return $this->update();
        }
        $result = $this->insert();
        if ($result && $updateIndex) {
            $this->setToIndex($result);
        }

        return $result;
    }
363855
public function Save(){
        if($this->transactionActive) {
            try {
                $this->commit();
                $this->exec("SET FOREIGN_KEY_CHECKS = 1;");
            } catch (\Exception $e) {
                $this->rollBack();
                echo $e->getMessage();
            }

            $this->transactionActive = false;
        }

        return false;
    }
1137715
public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    parent::postSave($storage, $update);
    if (\Drupal::moduleHandler()->moduleExists('pathauto')) {
      \Drupal::service('pathauto.generator')->updateEntityAlias($this, 'update');

      $trans = \Drupal::service('transliteration');
      $alias_manager = \Drupal::service('path.alias_manager');
      $alias_storage = \Drupal::service('path.alias_storage');

      $system_path = '/mespronos/day/'.$this->id().'/bet';
      $alias_day = $alias_manager->getAliasByPath('/mespronos/day/'.$this->id());
      $path_alias = str_replace('.html', '', $alias_day).'/pronostiquer.html';
      $urlAlias = $alias_manager->getAliasByPath($system_path);
      if ($urlAlias && $urlAlias != $path_alias) {
        $alias_storage->save($system_path, $path_alias);
      }

      $user_ids = \Drupal::entityQuery('user')->execute();
      $users = \Drupal::entityTypeManager()->getStorage("user")->loadMultiple($user_ids);
      foreach ($users as $user) {
        $system_path = '/mespronos/day/'.$this->id().'/results/user/'.$user->id();
        $path_alias = str_replace('.html', '', $alias_day).'/les-pronos-de-'.$trans->transliterate($user->label()).'.html';
        $urlAlias = $alias_manager->getAliasByPath($system_path);
        if ($urlAlias && $urlAlias != $path_alias) {
          $alias_storage->save($system_path, $path_alias);
        }
      }
    }
  }
1355204
function save() {
		// update changed collections
		$fields = $this->fieldConf;
		if ($fields)
			foreach($fields as $key=>$conf)
				if (!empty($this->fieldsCache[$key]) && $this->fieldsCache[$key] instanceof CortexCollection
					&& $this->fieldsCache[$key]->hasChanged())
					$this->set($key,$this->fieldsCache[$key]->getAll('_id',true));
		// perform event & save operations
		if ($new = $this->dry()) {
			if ($this->emit('beforeinsert')===false)
				return false;
			$result=$this->insert();
		} else {
			if ($this->emit('beforeupdate')===false)
				return false;
			$result=$this->update();
		}
		// m:m save cascade
		if (!empty($this->saveCsd)) {
			foreach($this->saveCsd as $key => $val) {
				if($fields[$key]['relType'] == 'has-many') {
					$relConf = $fields[$key]['has-many'];
					if ($relConf['hasRel'] == 'has-many') {
						$mmTable = $this->mmTable($relConf,$key);
						$mm = $this->getRelInstance(null, array('db'=>$this->db, 'table'=>$mmTable));
						$id = $this->get($relConf['localKey'],true);
						$filter = [$relConf['relField'].' = ?',$id];
						if ($relConf['isSelf']) {
							$filter[0].= ' OR '.$relConf['relField'].'_ref = ?';
							$filter[] = $id;
						}
						// delete all refs
						if (is_null($val))
							$mm->erase($filter);
						// update refs
						elseif (is_array($val)) {
							$mm->erase($filter);
							foreach($val as $v) {
								if ($relConf['isSelf'] && $v==$id)
									continue;
								$mm->set($key,$v);
								$mm->set($relConf['relField'].($relConf['isSelf']?'_ref':''),$id);
								$mm->save();
								$mm->reset();
							}
						}
						unset($mm);
					}
					elseif($relConf['hasRel'] == 'belongs-to-one') {
						$rel = $this->getRelInstance($relConf[0],$relConf,$key);
						// find existing relations
						$refs = $rel->find([$relConf[1].' = ?',$this->getRaw($relConf['relField'])]);
						if (is_null($val)) {
							foreach ($refs?:[] as $model) {
								$model->set($relConf[1],NULL);
								$model->save();
							}
							$this->fieldsCache[$key] = NULL;
						} else {
							if ($refs) {
								$ref_ids = $refs->getAll('_id');
								// unlink removed relations
								$remove_refs = array_diff($ref_ids,$val);
								foreach ($refs as $model)
									if (in_array($model->getRaw($relConf['relField']),$remove_refs)) {
										$model->set($relConf[1],null);
										$model->save();
									}
								// get new relation keys
								$val = array_diff($val,$ref_ids);
							} else
								$refs = new CortexCollection();
							if (!empty($val)) {
								// find models that need to be linked
								$new_refs = $rel->find([$relConf['relField'].' IN ?',$val]);
								foreach ($new_refs?:[] as $model) {
									// set relation to new models
									$model->set($relConf[1],$this->getRaw($relConf['relField']));
									$model->save();
									$refs->add($model);
								}
							}
							$this->fieldsCache[$key] = $refs;
						}
					}
				} elseif($fields[$key]['relType'] == 'has-one') {
					$val->save();
				}
			}
			$this->saveCsd = array();
		}
		$this->emit($new?'afterinsert':'afterupdate');
		return $result;
	}
801079
public function save()
    {
        $entries = $this->logBuffer->getEntries();

        $entrySkeleton = [
            'ts'    => $this->ts,
            'month' => $this->month,
            'year'  => $this->year
        ];

        $dimensionSkeleton = [
            'ts'    => $this->ts,
            'month' => $this->month,
            'year'  => $this->year
        ];

        /**
         * @var $e LogEntry
         */
        foreach ($entries as $e) {
            // build entry
            $entry = $entrySkeleton;
            $entry['entity'] = $e->getName();
            $entry['ref'] = $e->getRef();

            // check if we have attributes defined
            if (count($e->getAttributes()) > 0) {
                $entry['attributes'] = $e->getAttributes();
            }

            // insert or update the DAILY stat
            $this->mongo->update(self::ADB_STATS_DAILY, // match
                [
                    'entity' => $e->getName(),
                    'ref'    => $e->getRef(),
                    'ts'     => $this->ts
                ], // update
                [
                    '$inc'         => ['count' => $e->getIncrement()],
                    '$setOnInsert' => $entry
                ], // options
                ['upsert' => true]);

            // insert or update the MONTHLY stat
            unset($entry['ts']);
            $entry['month'] = $this->month;
            $entry['year'] = $this->year;
            $this->mongo->update(self::ADB_STATS_MONTHLY, // match
                [
                    'entity' => $e->getName(),
                    'ref'    => $e->getRef(),
                    'ts'     => $this->monthTs
                ], // update
                [
                    '$inc'         => ['count' => $e->getIncrement()],
                    '$setOnInsert' => $entry
                ], // options
                ['upsert' => true]);

            // insert dimensions for the entry
            $dimEntry = $dimensionSkeleton;
            $dimEntry['entity'] = $e->getName();

            /**
             * @var $dim LogDimension
             */
            foreach ($e->getDimensions() as $dim) {
                $dimEntry['name'] = $dim->getName();
                $dimEntry['value'] = $dim->getValue();

                $this->mongo->update(self::ADB_DIMS, // match
                    [
                        'name'   => $dim->getName(),
                        'value'  => $dim->getValue(),
                        'entity' => $e->getName(),
                        'ts'     => $this->ts
                    ], // update
                    [
                        '$inc'         => [
                            'count.' . $e->getRef() => $dim->getIncrement(),
                            'total'                 => $dim->getIncrement()
                        ],
                        '$setOnInsert' => $dimEntry
                    ], // options
                    ['upsert' => true]);
            }
        }

        // clear buffer
        $this->logBuffer = new LogBuffer();
    }