3 ШАГ. ПОСЛЕ СОХРАНЕНИЯ ОСНОВНОЙ МОДЕЛИ, ПРИСТУПАЕМ К СОХРАНЕНИЮ МОДЕЛИ С ДАННЫМИ
После сохранения элемента, установить связи с категориями и сохранить значение в таблицу "Data"
@param bool $insert
@param array $changedAttributes
163134
public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes); // TODO: Change the autogenerated stub

        //Сохранение связи в релативную таблицу
        if(!empty($this->_categories)){
            $this->saveDataRelationsTable( RelationsCategoriesItems::tableName(), ['item_id' => $this->id], ['category_id' => $this->categories]);
        }

        //Сохранение значений в таблицу "Data"
        $this->dataProperties->saveData($this);

        $this->trigger($insert ? self::EVENT_ITEM_AFTER_INSERT : self::EVENT_ITEM_AFTER_UPDATE);
    }
1179316
protected function proceedChangeSetsNeededByRelation()
    {
        $dbHandle = $this->getDatabase()->getDatabaseConnection();

        $tmpTable = Database::TABLE_TMP_DEPENDS_NEEDED;
        $neededByTable = Database::TABLE_CHANGESET_NEEDEDBY;
        $changeSetTable = Database::TABLE_CHANGESET;
        $patchSetTable = Database::TABLE_PATCHSET;

        $query = '
            INSERT INTO ' . $neededByTable . ' (`changeset`, `needed_by`, `tstamp`, `crdate`)
            SELECT
                ' . $changeSetTable . '.`id`,
                neededByChangeset.`id`,
                UNIX_TIMESTAMP(),
                UNIX_TIMESTAMP()
            FROM
                ' . $tmpTable . '
                INNER JOIN ' . $changeSetTable . ' AS neededByChangeset ON (
                    ' . $tmpTable . '.`identifier` = neededByChangeset.`identifier`
                    AND ' . $tmpTable . '.`number` = neededByChangeset.`number`
                )
                INNER JOIN gerrit_patchset ON (
                    neededByChangeset.`id` = ' . $patchSetTable . '.`changeset`
                    AND ' . $patchSetTable . '.`revision` = ' . $tmpTable . '.`revision`
                    AND ' . $patchSetTable . '.`ref` = ' . $tmpTable . '.`ref`
                )
                INNER JOIN ' . $changeSetTable . ' ON (
                    ' . $changeSetTable . '.`id` = ' . $tmpTable . '.`changeset`
                )
            WHERE
                ' . $tmpTable . '.`status` = ' . intval(Database::TMP_DEPENDS_NEEDED_STATUS_NEEDEDBY) . '
            GROUP BY
                ' . $changeSetTable . '.`id`, neededByChangeset.`id`
            ON DUPLICATE KEY UPDATE
                ' . $neededByTable . '.`tstamp` = UNIX_TIMESTAMP()';

        $dbHandle->exec($query);
    }
741100
protected function newQuery($insert = false)
	{
		$query = $this->connection->table($this->table);

		if (!$insert) {
			foreach ($this->extraColumns as $key => $value) {
				$query->where($key, '=', $value);
			}
		}

		if ($this->queryConstraint !== null) {
			$callback = $this->queryConstraint;
			$callback($query, $insert);
		}

		return $query;
	}
922413
public function insert($table, $datas = [], $INSERT = SQL::INSERT): array
    {
        if (\is_array($table)) {
            $datas = $table[SQL::VALUES] ?? $table[SQL::SET];
            $table = $this->getTable($table, SQL::INSERT);

            if (\is_string($datas)) {
                $INSERT = $datas;
            }
        }

        if (\is_string($INSERT) && \strpos($INSERT, ' ') !== false) {
            $INSERT = \array_map('\trim', \explode(' ', $INSERT));
        }

        if (\is_array($INSERT)) {
            $do = \in_array(SQL::REPLACE, $INSERT, true) ? 'REPLACE' : 'INSERT';
            $parts = [$do];

            $subs = [
                SQL::LOW_PRIORITY => 'LOW_PRIORITY',
                SQL::DELAYED => 'DELAYED',
            ];
            if ($do === SQL::INSERT) {
                $subs[SQL::HIGH_PRIORITY] = 'HIGH_PRIORITY';
            }
            foreach ($subs as $k => $sub) {
                if (\in_array($k, $INSERT, true)) {
                    $parts[] = $sub;
                    break;
                }
            }

            if ($do === SQL::INSERT && \in_array(SQL::IGNORE, $INSERT, true)) {
                $parts[] = 'IGNORE';
            }

            $INSERT = \implode(' ', $parts);
        } else {
            $INSERT = $INSERT === SQL::REPLACE ? 'REPLACE' : 'INSERT';
        }

        // Check indexed or associative array
        if (!isset($datas[0])) {
            $datas = [$datas];
        }

        $columns = \array_keys($datas[0]);

        $stack = [];
        $map = [];

        foreach ($datas as $data) {
            if (\array_keys($data) !== $columns) {
                throw new \InvalidArgumentException('Some rows contain inconsistencies');
            }

            $values = [];
            foreach ($columns as $key) {
                if ($raw = $this->buildRaw($data[$key], $map)) {
                    $values[] = $raw;
                    continue;
                }

                $values[] = $mapKey = $this->mapKey();

                if (!isset($data[$key])) {
                    $map[$mapKey] = [null, PDO::PARAM_NULL];
                } else {
                    $value = $data[$key];
                    $map[$mapKey] = $this->typeMap($value, \gettype($value));
                }

            }

            $stack[] = '(' . \implode(', ', $values) . ')';
        }

        $columns = \array_map([$this, 'columnQuote'], $columns);

        $sql = $INSERT . ' INTO ' . $this->tableQuote($table) .
            ' (' . \implode(', ', $columns) . ') VALUES ' . \implode(', ', $stack);

        return [$sql, $map];
    }
1181266
public function save($data = NULL, $replace = false)
    {
        if (is_null($data)) $data = $this->_data;
        if (!$data) return NULL;

        $this->createdAt && $data['created_at'] = $this->_getTime();
        $this->updatedAt && $data['updated_at'] = $this->_getTime();

        $columns = implode('`, `', array_keys($data));

        $type = $replace ? 'REPLACE INTO' : 'INSERT INTO';
        $sql = $type . ' ' . $this->getTableName() . ' (`' . $columns . '`) VALUES (' . rtrim(str_repeat('?, ', count($data)), ', ') . ')';

        return $this->execute($sql, array_values($data)) ? $this->getDb()->pdo['master']->lastInsertId() : NULL;
    }
1235056
public function save($insert = null) {
		if (is_null($insert)) {
			$insert = $this->dbId() ? false : true;
		}

		if ($insert) {
			$query = 'INSERT INTO `'.$this->table().'`';
		} else {
			$query = 'UPDATE `'.$this->table().'`';
		}

		$fields = $this->fields();

		$numset = 0;

		foreach ($fields as $field) {
			if ($field->auto === true && $insert && $field->field == $this->idVar()) {
				continue;
			}

			if ($this->{$field->field} == '' && $field->null) {
				$this->{$field->field} = null;
			} elseif ($this->{$field->field} == null && !$field->null) {
				$this->{$field->field} = '';
			}

			switch ($field->type) {
				case 'boolean':
					$this->{$field->field} = $this->{$field->field} ? true : false;
					if ($this->db()->driver() == 'mysql') {
						$this->{$field->field} = $this->{$field->field} ? 1 : 0;
					}
					break;

				case 'int':
					$this->{$field->field} = intval($this->{$field->field});
					break;

				case 'datetime':
					if ($this->{$field->field} == '0000-00-00 00:00:00' && $field->null) {
						$this->{$field->field} = null;
					}
					break;

				case 'date':
					if ($this->{$field->field} == '0000-00-00' && $field->null) {
						$this->{$field->field} = null;
					}
					break;
			}

			$this->{$field->field} = (!$this->{$field->field} && $field->null) ? null : $this->{$field->field};

			$query .= !$numset ? ($insert ? '(' : ' SET ') : ',';
			if ($insert) {
				$query .= ' `'.$field->field.'` ';
			} else {
				if ($field->field != $this->idVar()) {
					$query .= ' `'.$field->field.'`=:'.$field->field;
				} else {
					// should proabably be cleaned up a bit
					$query = substr($query, 0, -5);
					$numset--;
				}
			}

			$fs[$field->field] = $this->{$field->field};

			$numset++;

		}

		if ($insert) {
			$query .= ' ) VALUES (';
			$numset = 0;

			foreach ($fields as $field) {
				if ($field->auto === true) {
					continue;
				}

				$query .= !$numset ? '' : ',';
				$query .= ' :'.$field->field;
				$numset++;
			}

			$query .= ')';
		} else {
			$query .= ' WHERE '.$this->idVar().'=:id';
			$fs['id'] = $this->{$this->idVar()};
		}

		$stmt = $this->db()->query($query, $fs);

		if ($insert) {
			$this->{$this->idVar()} = $this->db()->db()->lastInsertId($fields[$this->idVar()]->sequence ? $fields[$this->idVar()]->sequence : null);
		}

		return $this;
	}
736513
public function beforeSave($insert)
	{		
		if (parent::beforeSave($insert)) 
		{
			if ($insert) 
			{
				$this->created_at=$this->updated_at=time();
				$this->author_id=\Yii::$app->user->identity->id;
			}
			else
			{
				$this->updated_at=time();
				$a = strptime($this->created_at, '%Y-%m-%d');
				$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday']+1, $a['tm_year']+1900);				
				$this->created_at = $timestamp;		
			}
			return true;
		} 
		return false;
	}
79758
public function updateAttributes($index, array $attrs, array $values, $mva = false)
    {
        // verify everything
        assert(is_string($index));
        assert(is_bool($mva));

        assert(is_array($attrs));
        foreach ($attrs as $attr) {
            assert(is_string($attr));
        }

        assert(is_array($values));
        foreach ($values as $id => $entry) {
            assert(is_numeric($id));
            assert(is_array($entry));
            assert(count($entry) == count($attrs));
            foreach ($entry as $v) {
                if ($mva) {
                    assert(is_array($v));
                    foreach ($v as $vv) {
                        assert(is_int($vv));
                    }
                } else {
                    assert(is_int($v));
                }
            }
        }

        // build request
        $this->_MBPush();
        $req = pack('N', strlen($index)).$index;

        $req .= pack('N', count($attrs));
        foreach ($attrs as $attr) {
            $req .= pack('N', strlen($attr)).$attr;
            $req .= pack('N', $mva ? 1 : 0);
        }

        $req .= pack('N', count($values));
        foreach ($values as $id => $entry) {
            $req .= $this->sphPackU64($id);
            foreach ($entry as $v) {
                $req .= pack('N', $mva ? count($v) : $v);
                if ($mva) {
                    foreach ($v as $vv) {
                        $req .= pack('N', $vv);
                    }
                }
            }
        }

        // connect, send query, get response
        if (!($fp = $this->_Connect())) {
            $this->_MBPop();

            return -1;
        }

        $len = strlen($req);
        $req = pack('nnN', SEARCHD_COMMAND_UPDATE, VER_COMMAND_UPDATE, $len).$req; // add header
        if (!$this->_Send($fp, $req, $len + 8)) {
            $this->_MBPop();

            return -1;
        }

        if (!($response = $this->_GetResponse($fp, VER_COMMAND_UPDATE))) {
            $this->_MBPop();

            return -1;
        }

        // parse response
        list(, $updated) = unpack('N*', substr($response, 0, 4));
        $this->_MBPop();

        return $updated;
    }
1082254
public function afterSave($insert, $changedAttributes)
    {
        if ($insert) {
            //开始机器审核
            Yii::$app->queue->push(new ScanTextJob([
                'modelClass' => get_class($this), 'modelId' => $this->id, 'scenario' => 'new', 'category' => 'comment'
            ]));
            $this->source->updateCountersAsync(['comments' => 1]);
            try {
                Yii::$app->notification->send($this->source->user, $this);
            } catch (InvalidConfigException $e) {
            }
        }
        parent::afterSave($insert, $changedAttributes);
    }
1370091
protected function hasChanges($changes, $attributes = null)
    {
        // If no specific attributes were provided, we will just see if the dirty array
        // already contains any attributes. If it does we will just return that this
        // count is greater than zero. Else, we need to check specific attributes.
        if (empty($attributes)) {
            return count($changes) > 0;
        }

        // Here we will spin through every attribute and see if this is in the array of
        // dirty attributes. If it is, we will return true and if we make it through
        // all of the attributes for the entire array we will return false at end.
        foreach (Arr::wrap($attributes) as $attribute) {
            if (array_key_exists($attribute, $changes)) {
                return true;
            }
        }

        return false;
    }
564472
public function upsert($table, $insertFieldValues, $updateFieldValues = [], $primaryKey = null)
    {
        if (!$primaryKey) {
            $primaryKey = (string)key($insertFieldValues);
        }

        if ($this->query($table)->whereEq($primaryKey, $insertFieldValues[$primaryKey])->exists()) {
            $bind = [];
            $updates = [];
            foreach ($updateFieldValues as $k => $v) {
                $field = is_string($k) ? $k : $v;
                if ($primaryKey === $field) {
                    continue;
                }

                if (is_int($k)) {
                    $updates[] = "[$field]=:$field";
                    $bind[$field] = $insertFieldValues[$field];
                } elseif ($v instanceof AssignmentInterface) {
                    $v->setFieldName($k);
                    $updates[] = $v->getSql();
                    /** @noinspection SlowArrayOperationsInLoopInspection */
                    $bind = array_merge($bind, $v->getBind());
                } else {
                    $updates[] = $v;
                }
            }
            return $this->update($table, $updates, [$primaryKey => $insertFieldValues[$primaryKey]], $bind);
        } else {
            return $this->insert($table, $insertFieldValues);
        }
    }
95863
public function beforePropertyModelSave(Property &$property, $insert)
    {
        if ($property->canTranslate()) {
            $property->data_type = Property::DATA_TYPE_INVARIANT_STRING;
        }
        $data = Yii::$app->request->post(Property::PACKED_HANDLER_PARAMS);
        if (empty($data) === true) {
            $data = ArrayHelper::getValue(
                Yii::$app->request->post($property->formName()),
                'params.' . Property::PACKED_HANDLER_PARAMS,
                []
            );
        }
        $param = $property->params;
        if (empty($data) === false) {
            $params[Property::PACKED_HANDLER_PARAMS] = $data;
            $property->params = $params;
            $property->packAttributes();
        }
        return parent::beforePropertyModelSave($property, $insert);
    }
70403
public void insertAttributeValue(String attributeName, CmsEntity value, int index) {

        if (m_entityAttributes.containsKey(attributeName)) {
            m_entityAttributes.get(attributeName).add(index, value);
        } else {
            setAttributeValue(attributeName, value);
        }
        registerChangeHandler(value);
        fireChange();
    }
1089525
public function insert($insert)
    {
        $this->type = self::INSERT;

        $this->from($insert);

        return $this;
    }
961249
public function insert($table_name, array $data) {
            Event::dispatch(EventData::forBefore(Event::BEFORE_INSERT, $table_name, $data), $data);

            $q = $this->config->getSystemIdentifierQuote();
            $fields = [];
            $data_values = "";
            $statement_params = [];
            $null_params = [];

            foreach ($data as $field_name => $value) {
                $fields[] = "\n$q" . $field_name . $q;
                if (strtolower($value) == 'null' || is_null($value)) {
                    $data_values .= 'NULL,';
                    $null_params[ $field_name ] = 'NULL';
                } else {
                    $data_values .= ':' . $field_name . ',';
                    $statement_params[ ':' . $field_name ] = $value;
                }
            }

            $full_param_list = array_merge($statement_params, $null_params);

            $fields = implode(',', $fields);
            $data_values = substr($data_values, 0, -1);
            $sql_query = "INSERT INTO \n$q" . $table_name . "$q ( " . $fields . " )\n VALUES (" . $data_values . ")";
            if ($this->config->db_type === 'pgsql') {
                $sql_query .= "\nRETURNING id;\n";
            }

            try {
                $stmt = $this->db_connection->prepare($sql_query);
                if ($statement_params) {
                    foreach ($statement_params as $k => $v) {
                        $stmt->bindValue($k, $v);
                    }
                }
                $stmt->execute();
            } catch (Exception $ex) {
                Event::dispatch(EventData::forException($ex, $sql_query, $full_param_list));
                throw new QueryException($ex->getMessage(), $ex->getCode(), $ex);
            }

            if ($this->config->db_type === 'pgsql') {
                $insert_id = $stmt->fetchColumn(0);
            } else {
                $insert_id = $this->db_connection->lastInsertId();
            }

            $rows_affected = empty($insert_id) ? 0 : 1;
            Event::dispatch(EventData::forAfter(Event::AFTER_INSERT, $table_name, $full_param_list, $sql_query, $rows_affected, $insert_id));

            return $insert_id;
        }
1316648
public function updateInsertQuery($insert)
    {
        if ($this->relation) {
            $insert = $this->relation->dsql;
        }

        $insert->set(
            $this->actual_field ?: $this->short_name,
            $this->getSQL()
        );

        return $this;
    }
784723
function insert($table, array $bind)
    {
        $sql = $this->insertSql($table, $bind);
        // execute the statement and return the number of affected rows
        $stmt = $this->wrappedAdapter->query($sql, array_values($bind));
        $result = $stmt->rowCount();
        return $result;
    }