Save the selected record.
This will do an INSERT or UPDATE as appropriate

@param boolean $automatic_reload Whether or not to automatically reload

@return ActiveRecord
328230
public function save($automatic_reload = true)
    {
        // Run Pre-saver.
        $this->preSave();

        // Run Field Fixer.
        $this->__fieldFix();

        // Calculate row to save_down
        $this->__calculateSaveDownRows();
        $primary_key_column = $this->getIDField();

        // Make an array out of the objects columns.
        $data = array();
        foreach ($this->_columns as $column) {
            // Never update the primary key. Bad bad bad. Except if we're versioned.
            if ($column != $primary_key_column ||
              $this instanceof VersionedActiveRecord ||
              $this->_force_insert
            ) {
                $data["`{$column}`"] = $this->$column;
            }
        }

        // If we already have an ID, this is an update.
        $database = DatabaseLayer::getInstance();
        if (!$this->getId() ||
          (property_exists($this, '_is_versioned') && $this->_is_versioned == true) ||
          $this->_force_insert
        ) {
            $operation = $database->insert($this->getTableName(), $this->getTableAlias());
            $this->_force_insert = false;
        } else { // Else, we're an insert.
            $operation = $database->update($this->getTableName(), $this->getTableAlias());
        }

        $operation->setData($data);

        if ($this->getId() && $primary_key_column) {
            $operation->condition($primary_key_column, $this->$primary_key_column);
            $operation->execute();
        } else { // Else, we're an insert.
            $new_id = $operation->execute($this->getClass());
            if ($primary_key_column) {
                $this->$primary_key_column = $new_id;
            }
        }

        // Expire cache.
        if (DatabaseLayer::getInstance()->useCache()) {
            $cache = DatabaseLayer::getInstance()->getCache();
            $cache->delete($this->getCacheIdentifier());
        }

        // Expire any existing copy of this object.
        SearchIndex::getInstance()->expire(get_called_class() . "/" . $this->getTableName(), $this->getId());

        if ($automatic_reload && $primary_key_column) {
            $this->reload();
        }

        // Run Post Save.
        $this->postSave();

        // Return object. Should this return true/false based on success instead?
        return $this;
    }
146648
def associated_records_to_validate_or_save(association,
                                               new_record,
                                               autosave)
      if new_record || autosave
        association && association.target
      else
        association.target.find_all(&:new_record?)
      end
    end
644205
public function save() :bool {
		
		// if an id already exists
		if($this->_['id']) {
			// we can update and return the number of affected rows (0 on error, 1 on success)
			return (bool) self::_update()
				->set($this->__toArray(true, true))
				->where(['id'=>$this->_['id']])
				->execute();
		}
		// this is a new record
		else {
			// try to insert it
			$inserted_object = self::create($this->__toArray(true, true));
			// if insertion succeeded, return true
			if($inserted_object) {
				// clone ourselves with what the database returneds, a full fledged object
				$this->replicate($inserted_object);
				// return success
				return true;
			}
			// didnt insert
			else {
				// failure feedback
				return false;
			}
		}
		
	}
1118901
public function save(array $options = [])
    {
        $query = $this->newModelQuery();

        // If the "saving" event returns false we'll bail out of the save and return
        // false, indicating that the save failed. This provides a chance for any
        // listeners to cancel save operations if validations fail or whatever.
        if ($this->fireModelEvent('saving') === false) {
            return false;
        }

        // If the model already exists in the database we can just update our record
        // that is already in this database using the current IDs in this "where"
        // clause to only update this model. Otherwise, we'll just insert them.
        if ($this->exists) {
            $saved = $this->isDirty() ?
                        $this->performUpdate($query) : true;
        }

        // If the model is brand new, we'll insert it into our database and set the
        // ID attribute on the model to the value of the newly inserted row's ID
        // which is typically an auto-increment value managed by the database.
        else {
            $saved = $this->performInsert($query);

            if (! $this->getConnectionName() &&
                $connection = $query->getConnection()) {
                $this->setConnection($connection->getName());
            }
        }

        // If the model is successfully saved, we need to do a few more things once
        // that is done. We will call the "saved" method here to run any actions
        // we need to happen after a model gets successfully saved right here.
        if ($saved) {
            $this->finishSave($options);
        }

        return $saved;
    }
1328186
public function save()
    {
        $this->fireModelEvent('saving', false);

        // If the model already exists in the database we can just update our record
        // that is already in this database using the current IDs in this "where"
        // clause to only update this model. Otherwise, we'll just insert them.
        if ($this->exists) {
            $saved = $this->performUpdate();
        }

        // If the model is brand new, we'll insert it into our database and set the
        // ID attribute on the model to the value of the newly inserted row's ID
        // which is typically an auto-increment value managed by the database.
        else {
            $saved = $this->performCreate();
        }

        if ($saved) {
            $this->fireModelEvent('saved', false);
        }

        return $saved;
    }
7061
public function save()
    {
    	if($this->exists())
    	{
			// update
			$query = new Query(static::table());
			$query->update($this->getData(), $this->getIdentifyCondition());
			return $query->execute();
    	}
    	else
    	{
    		// insert
			$query = new Query(static::table());
			$query->insert($this->getData());
            if($query->execute())
                $this->from_db = true;
            return $query->success();
    	}
    }
107337
public function beforeSave()
    {
        /* @var $model ActiveRecord */
        $model = $this->owner;
        foreach ($this->attributes as $attr => $options) {
            $this->ensureAttributes($attr, $options);
            if ($file = UploadedFile::getInstance($model, $attr)) {
                $this->createDirIfNotExists($attr);
                if (!$model->isNewRecord) {
                    $this->deleteFiles($attr);
                }
                $fileName = uniqid() . '.' . $file->extension;
                $model->{$attr} = $fileName;
                $file->saveAs($this->getSavePath($attr) . $fileName);
            } elseif (isset($model->oldAttributes[$attr])) {
                $model->{$attr} = $model->oldAttributes[$attr];
            }
        }
    }
1221543
public function save($table, $data, $id = 'id', $auto_id = true)
    {
        // Update
        if (isset($data[$id]) && $this->getFieldById($table, $id, $this->escape($data[$id]), $id) !== false) {
            try {
                return $this->updateById($table, $data, $id);
            } catch (\Exception $e) {
                throw $e;
            }

            // Insert
        } else {
            try {
                if ($auto_id) {
                    unset($data[$id]);
                }
                return $this->insertId($table, $data);
            } catch (\Exception $e) {
                throw $e;
            }
        }
    }
990033
public function save($options = TRUE)
  {
    // Update references to referenced models
    $this->_update_references();

    // Convert old bool argument to options array
    if (is_bool($options)) {
      $options = array('w' => 1);
    }
    if (isset($options['safe'])) {
      $options['w'] = (int) $options['safe']; $options['j'] = (bool) $options['safe'];
      unset($options['safe']);
    }
    if ( ! isset($options['w'])) {
      $options['w'] = $this->db()->db()->w == 0 ? 1 : $this->db()->db()->w;
    }

    // Insert new record if no _id or _id was set by user
    if( ! isset($this->_object['_id']) || isset($this->_changed['_id']))
    {
      $action = self::SAVE_INSERT;

      $this->before_save($action);

      $values = array();
      foreach($this->_changed as $name => $_true)
      {
        $values[$name] = $this->_object[$name];
      }

      if(empty($values))
      {
        throw new MongoException('Cannot insert empty array.');
      }

      $err = $this->collection()->insert($values, $options);

      if($err['err'] && (! empty($options['w']) || ! empty($options['j'])))
      {
        throw new MongoException('Unable to insert '.get_class($this).': '.$err['err']);
      }

      if ( ! isset($this->_object['_id']))
      {
        // Store (assigned) MongoID in object
        $this->_object['_id'] = $values['_id'];
        $this->_loaded = TRUE;
      }

      // Save any additional operations
      /** @todo  Combine operations into the insert when possible to avoid this update */
      if($this->_operations)
      {
        if( ! $this->collection()->update(array('_id' => $this->_object['_id']), $this->_operations))
        {
          $err = $this->db()->lastError();
          throw new MongoException('Update of '.get_class($this).' failed: '.$err['err']);
        }
      }
    }

    // Update assumed existing document
    else
    {
      $action = self::SAVE_UPDATE;

      $this->before_save($action);

      if($this->_changed)
      {
        foreach($this->_changed as $name => $_true)
        {
          $this->_operations['$set'][$name] = $this->_object[$name];
        }
      }

      if($this->_operations)
      {
        if( ! $this->collection()->update(array('_id' => $this->_object['_id']), $this->_operations))
        {
          $err = $this->db()->lastError();
          throw new MongoException('Update of '.get_class($this).' failed: '.$err['err']);
        }
      }
    }

    $this->_changed = $this->_operations = array();

    $this->after_save($action);

    return $this;
  }
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;
	}
922002
def update(attrs, safe = false)
      self.attributes = attrs
      if new_record?
        _root.send(:_save, safe) if _root
        _save(safe)
      else
        _update_attributes(converted_attributes(attrs), safe)
      end
    end
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;
	}
1331954
def save(self, *args, **kwargs):
        
        # auto fill updated field with current time unless explicitly disabled
        auto_update = kwargs.get('auto_update', True)
        if auto_update:
            self.updated = now()

        # remove eventual auto_update
        if 'auto_update' in kwargs:
            kwargs.pop('auto_update')

        super(BaseDate, self).save(*args, **kwargs)
1079523
public function save() {
		/**
		 * Fires saving action.
		 *
		 * @param static $wp_object Current object instance.
		 */
		do_action( $this->prefix( 'saving' ), $this );

		if ( $this->recently_created ) {
			$this->recently_created = false;
		}

		// Allow sub-class overwrite before_save method, here we can
		// validate the attribute data before save or doing something else.
		$this->before_save();

		// If the object already exists we can update changes.
		// Otherwise, we'll just insert them.
		if ( $this->exists() ) {
			$saved = $this->is_dirty() ? $this->update_object() : true;
		} else {
			$saved = $this->insert_object();
		}

		if ( $saved ) {
			$this->finish_save();

			/**
			 * Fires saved action.
			 *
			 * @param static $wp_object Current object instance.
			 */
			do_action( $this->prefix( 'saved' ), $this );

			$this->sync_original();
		}

		return $saved;
	}
169083
public function insert()
	{
		$res = \DB::insert(call_user_func($this->model.'::table'), array_keys($this->values))
			->values(array_values($this->values))
			->execute($this->write_connection);

		// Failed to save the new record
		if ($res[1] === 0)
		{
			return false;
		}

		return $res[0];
	}
166567
private function insert()
    {
        $insert = $this->dsql();

        // Performs the actual database changes. Throw exception if problem occurs
        foreach ($this->elements as $name => $f) {
            if ($f instanceof Field) {
                if (!$f->editable() && !$f->system()) {
                    continue;
                }
                if (!isset($this->dirty[$name]) && $f->defaultValue() === null) {
                    continue;
                }

                $f->updateInsertQuery($insert);
            }
        }
        $this->hook('beforeInsert', array(&$insert));
        //delayed is not supported by INNODB, but what's worse - it shows error.
        //if($this->_save_as===false)$insert->option_insert('delayed');
        $id = $insert->insert();
        if ($id == 0) {
            // no auto-increment column present
            $id = $this->get($this->id_field);

            if ($id === null && $this->_save_as !== false) {
                throw $this->exception('Please add auto-increment ID column to your table or specify ID manually');
            }
        }
        $res = $this->hook('afterInsert', array($id));
        if ($res === false) {
            return $this;
        }

        if ($this->_save_as === false) {
            return $this->unload();
        }
        if ($this->_save_as) {
            $this->unload();
        }
        $o = $this->_save_as ?: $this;

        if ($this->fast && !$this->_save_as) {
            $this[$this->id_field] = $this->id = $id;

            return $this;
        }
        $res = $o->tryLoad($id);
        if (!$res->loaded()) {
            throw $this->exception('Saved model did not match conditions. Save aborted.');
        }

        return $res;
    }
575112
public function save()
    {
        if (!$this->token->validate('save_automated_logout')) {
            $this->error->add($this->token->getErrorMessage());

            $this->flash('error', $this->error);

            // Redirect away from this save endpoint
            return $this->factory->redirect($this->action());
        }

        $post = $this->request->request;
        // Save the posted settings
        $this->config->save(self::ITEM_IP, filter_var($post->get('invalidateOnIPMismatch'), FILTER_VALIDATE_BOOLEAN));
        $this->config->save(self::ITEM_USER_AGENT, filter_var($post->get('invalidateOnUserAgentMismatch'), FILTER_VALIDATE_BOOLEAN));
        $this->config->save(self::ITEM_INVALIDATE_INACTIVE_USERS, filter_var($post->get('invalidateInactiveUsers'), FILTER_VALIDATE_BOOLEAN));
        $this->config->save(self::ITEM_INVALIDATE_INACTIVE_USERS_TIME, filter_var($post->get('inactiveTime'), FILTER_VALIDATE_INT));

        $this->flash('message', t('Successfully saved Session Security settings'));

        // Redirect away from this save endpoint
        return $this->factory->redirect($this->action());
    }