Link the related models.
If the models have not been changed, nothing will be done.
Related records will be linked to the owner model using the BaseActiveRecord `link()` method.
@throws Exception
513410
public function afterSave()
    {
        if ($this->_relationsSaveStarted === false) {
            /** @var BaseActiveRecord $owner */
            $owner = $this->owner;
            $this->_relationsSaveStarted = true;
            // Populate relations with updated values
            foreach ($this->_newRelationValue as $name => $value) {
                $owner->populateRelation($name, $value);
            }
            try {
                foreach ($this->_relations as $relationName) {
                    if (array_key_exists($relationName, $this->_oldRelationValue)) { // Relation was not set, do nothing...
                        Yii::debug("Linking {$relationName} relation", __METHOD__);
                        /** @var ActiveQuery $relation */
                        $relation = $owner->getRelation($relationName);
                        if ($relation->multiple === true) { // Has many relation
                            $this->_afterSaveHasManyRelation($relationName);
                        } else { // Has one relation
                            $this->_afterSaveHasOneRelation($relationName);
                        }
                        unset($this->_oldRelationValue[$relationName]);
                    }
                }
            } catch (Exception $e) {
                Yii::warning(get_class($e) . ' was thrown while saving related records during afterSave event: ' . $e->getMessage(), __METHOD__);
                $this->_rollback();
                /***
                 * Sadly mandatory because the error occurred during afterSave event
                 * and we don't want the user/developper not to be aware of the issue.
                 ***/
                throw $e;
            }
            $owner->refresh();
            $this->_relationsSaveStarted = false;
        }
    }
1052014
public function executePendingLinkage()
    {
        foreach ($this->pendingLinks as $item) {
            /** @var ShareOneOrMany $rel */
            $rel = $item['relation'];
            if ($item['link']) {
                $rel->link($this, $item['entity']);
            } else {
                $rel->unlink($this, $item['entity']);
            }
        }

        $this->pendingLinks = [];
    }
369399
@Override
  public Boolean call() throws Exception {

    ProcessRecord updatedRecord = null;
    Connection hbaseConnection = null;
    try {
      hbaseConnection = ConnectionFactory.createConnection(hbaseConf);
      // Connect only when needed.
      ProcessRecordService processRecordService =
          new ProcessRecordService(hbaseConf, hbaseConnection);

      updatedRecord =
          processRecordService.setProcessState(processRecord, newState);
    } finally {
      if (hbaseConnection != null) {
        hbaseConnection.close();
      }
    }

    if ((updatedRecord != null)
        && (updatedRecord.getProcessState() == newState)) {
      return true;
    }
    return false;
  }
739006
public void updateRelations() throws Exception {

        if (m_detectedVersion > 6) {
            // skip if not updating from 6.x
            return;
        }
        I_CmsReport report = new CmsShellReport(m_cms.getRequestContext().getLocale());

        report.println(Messages.get().container(Messages.RPT_START_UPDATE_RELATIONS_0), I_CmsReport.FORMAT_HEADLINE);

        String storedSite = m_cms.getRequestContext().getSiteRoot();
        CmsProject project = null;
        try {
            String projectName = "Update relations project";
            try {
                // try to read a (leftover) unlock project
                project = m_cms.readProject(projectName);
            } catch (@SuppressWarnings("unused") CmsException e) {
                // create a Project to unlock the resources
                project = m_cms.createProject(
                    projectName,
                    projectName,
                    OpenCms.getDefaultUsers().getGroupAdministrators(),
                    OpenCms.getDefaultUsers().getGroupAdministrators(),
                    CmsProject.PROJECT_TYPE_TEMPORARY);
            }

            m_cms.getRequestContext().setSiteRoot(""); // change to the root site
            m_cms.getRequestContext().setCurrentProject(project);

            List<I_CmsResourceType> types = OpenCms.getResourceManager().getResourceTypes();
            int n = types.size();
            int m = 0;
            Iterator<I_CmsResourceType> itTypes = types.iterator();
            while (itTypes.hasNext()) {
                I_CmsResourceType type = itTypes.next();
                m++;
                report.print(
                    org.opencms.report.Messages.get().container(
                        org.opencms.report.Messages.RPT_SUCCESSION_2,
                        String.valueOf(m),
                        String.valueOf(n)),
                    I_CmsReport.FORMAT_NOTE);
                report.print(
                    org.opencms.report.Messages.get().container(
                        org.opencms.report.Messages.RPT_ARGUMENT_1,
                        type.getTypeName()));
                report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_DOTS_0));

                if (type instanceof I_CmsLinkParseable) {
                    try {
                        CmsXmlContentRepairSettings settings = new CmsXmlContentRepairSettings(m_cms);
                        settings.setIncludeSubFolders(true);
                        settings.setVfsFolder("/");
                        settings.setForce(true);
                        settings.setResourceType(type.getTypeName());

                        CmsXmlContentRepairThread t = new CmsXmlContentRepairThread(m_cms, settings);
                        t.start();

                        synchronized (this) {
                            t.join();
                        }
                        report.println(
                            org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0),
                            I_CmsReport.FORMAT_OK);
                    } catch (Exception e) {
                        report.println(
                            org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_ERROR_0),
                            I_CmsReport.FORMAT_ERROR);
                        report.addError(e);
                        // log the error
                        e.printStackTrace(System.err);
                    }
                } else {
                    report.println(
                        org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_SKIPPED_0),
                        I_CmsReport.FORMAT_WARNING);
                }
            }
        } finally {
            try {
                if (project != null) {
                    try {
                        m_cms.unlockProject(project.getUuid()); // unlock everything
                        OpenCms.getPublishManager().publishProject(
                            m_cms,
                            report,
                            OpenCms.getPublishManager().getPublishList(m_cms));
                        OpenCms.getPublishManager().waitWhileRunning();
                    } finally {
                        m_cms.getRequestContext().setCurrentProject(m_cms.readProject(CmsProject.ONLINE_PROJECT_ID));
                    }
                }
            } finally {
                m_cms.getRequestContext().setSiteRoot(storedSite);
            }
            report.println(
                Messages.get().container(Messages.RPT_FINISH_UPDATE_RELATIONS_0),
                I_CmsReport.FORMAT_HEADLINE);
        }
    }
743990
public function onConstruct()
    {
        $this->userLinkedSourcesModel = new UserLinkedSources();
        $this->userModel = new Users();

        if (!isset($this->config->jwt)) {
            throw new Exception('You need to configure your app JWT');
        }
    }
1337084
private void handleBaseUriLink(EntityBuilder builder, String baseUri) {
        if (StringUtils.isBlank(baseUri)) {
            return;
        }
        Link link = LinkBuilder.newInstance().setRelationship(Link.RELATIONSHIP_BASEURI).setHref(baseUri).build();
        builder.addLink(link);
    }
427393
protected function getModel()
	{
		if (!$model = $this->owner) {
			throw new \Exception('Model is not been initialized properly.');
		}
		if (!$model instanceof ActiveRecord) {
			throw new \Exception(sprintf('Behavior must be applied to the ActiveRecord model class and it\'s iheritants, the unsupported class provided: `%s`', get_class($model)));
		}

		return $model;
	}
98061
public void commit() throws DBException
    {
        if (DBConstants.FALSE.equalsIgnoreCase(this.getProperty(SQLParams.AUTO_COMMIT_PARAM)))
        {
            if (!(this.getDatabaseOwner() instanceof RecordOwner))
                throw new DatabaseException("Transactions requires DB RecordOwnership");
        }
        else
            throw new DatabaseException("Auto-commit enabled");
    }
1284851
protected function linkUnlinkProcess(ModelInterface $model, $link = true, array $extra = [])
    {
        $primaryModel = $this->getPrimaryModel();
        if ($primaryModel && empty($primaryModel->pk)) {
            throw new Exception('Unable to '.($link ? 'link' : 'unlink').' models: the primary key of '.get_class($primaryModel).' is '.$primaryModel->pk.'.');
        }

        if ($this->through && $link) {
            /** @var \Mindy\Orm\Model $throughModel */
            $throughModel = new $this->through();
            if (empty($this->throughLink)) {
                $from = $this->primaryModelColumn;
                $to = $this->modelColumn;
            } else {
                list($from, $to) = $this->throughLink;
            }
            list($through, $created) = $throughModel->objects()->getOrCreate([
                $from => $this->primaryModel->pk,
                $to => $model->pk,
            ]);

            return $through->pk;
        }
        $db = $this->primaryModel->getConnection();
        $builder = QueryBuilderFactory::getQueryBuilder($db);
        $data = array_merge([
                $this->primaryModelColumn => $this->primaryModel->pk,
                $this->modelColumn => $model->pk,
            ], $extra);
        if ($link) {
            $state = $model->getConnection()->insert(
                $builder->getQuotedName(TableNameResolver::getTableName($this->relatedTable)),
                $data
            );
        } else {
            $state = $model->getConnection()->delete(
                $builder->getQuotedName(TableNameResolver::getTableName($this->relatedTable)),
                $data
            );
        }

        return $state;
    }
986868
protected function serializeRelationship(Model $owner, $relationship = null, RelationshipMetadata $relMeta, AdapterInterface $adapter)
    {
        if ($relMeta->isOne()) {
            if (is_array($relationship)) {
                throw SerializerException::badRequest('Invalid relationship value.');
            }
            $serialized = $this->serializeHasOne($owner, $relationship, $adapter);
        } elseif (is_array($relationship) || null === $relationship) {
            $serialized = $this->serializeHasMany($owner, $relationship, $adapter);
        } else {
            throw SerializerException::badRequest('Invalid relationship value.');
        }

        $ownerMeta = $owner->getMetadata();
        $serialized['links'] = [
            'self'      => $adapter->buildUrl($ownerMeta, $owner->getId(), $relMeta->getKey()),
            'related'   => $adapter->buildUrl($ownerMeta, $owner->getId(), $relMeta->getKey(), true),
        ];
        return $serialized;
    }
1285238
protected void initModel() throws Exception {
        Model.getSingleton().init(getControlOverrides());
        Model.getSingleton().getOptionsParam().setGUI(getArgs().isGUI());
    }
633982
public void add(Rec fieldList) throws DBException
    {
        if (this.getBaseRecord() == fieldList)    // If so, set the correct record for write
            fieldList = this.moveToCurrentRecord((Record)fieldList);   // Hopefully, they supplied a default record type and this will switch it.
        if (fieldList == null)
            throw new DBException("Unknown shared record type");
        if (fieldList == this.getBaseRecord())
            super.add(fieldList);
        else
        {
            this.getBaseRecord().matchListeners((Record)fieldList, false, true, true, true, true);      // Clone the listeners that are not there already.
            fieldList.getTable().add(fieldList);
        }
    }
1132619
public function setRelation($name, $related_object)
    {
        //if no related object is supplied, set it to false (an array
        //value of null will not pass an isset() check on the
        //relation_objects array).
        if (!$related_object) {
            $related_object = false;
        }

        $this->relation_objects[$name] = $related_object;
    }
55211
protected function addRelation()
    {
        if ($this->relationType == 'hasAndBelongsToMany')
        {
            $junction = $this->getJunction();

            try
            {
                Validate::table($junction)->exists();
            }
            catch (dbException $e)
            {
                Database::create($junction, [
                    $this->tables['local'] . '_id'   => 'integer',
                    $this->tables['foreign'] . '_id' => 'integer',
                ]);

                $this->insertRelationData($junction, $this->tables['local'], 'hasMany', [
                    'local'   => $this->tables['local'] . '_id',
                    'foreign' => $this->keys['local']
                ]);

                $this->insertRelationData($junction, $this->tables['foreign'], 'hasMany', [
                    'local'   => $this->tables['foreign'] . '_id',
                    'foreign' => $this->keys['foreign']
                ]);
            }
        }
        $this->insertRelationData($this->tables['local'], $this->tables['foreign'], $this->relationType, $this->keys);
    }
4860
public function setRelatedModel(Model $model) {
        $this->_relatedModel = $model;
        $this->setRelatedClass(get_class($model));

        return $this;
    }
274466
public function belongsTo(Model $relatedModel, $foreignKey)
    {
        if ($relatedModel->isIgnored()) {
            return;
        }

        $this->relations->add(
            new Relations\BelongsTo($this, $relatedModel, $foreignKey)
        );
    }
280366
private void connectReferences() {
        // ready to associate initalized beans with references
        for (Bean bean : beans.values()) {
            for (JpaRef ref : refs.get(bean.getId())) {
                BeanId target = ref.getTarget();
                Bean targetBean = beans.get(target);
                target.setBean(targetBean);
                bean.addReference(ref.getPropertyName(), target);
            }
        }
    }