Insert a belongsTo foreign key relationship.

@param  Model $record
@param  Relation $relation
@param  int $columnValue
@return void
426268
protected function insertBelongsTo(Model $record, Relation $relation, $columnValue)
    {
        $foreignKeyName = $relation->getForeignKey();
        $foreignKeyValue = $this->generateKey($columnValue);
        $record->$foreignKeyName = $foreignKeyValue;
    }
496057
public function InsertRelation( \rstoetter\libsqlphp\cKEY_COLUMN_USAGE_Entry $obj ) {

        if ( is_null( $obj->m_TABLE_NAME ) ) {
            die( "\n cKEY_COLUMN_USAGE_Entry mit is_null( m_TABLE_NAME ) " );
        }
	
        $obj_found = $this->SearchByKey( $obj->m_TABLE_NAME );
        if ( $obj_found === false ) {            
        
            // if the referencing table does not exist, then insert it in the tree
        
            $obj_new = new cKeyColumnUsageTreeNode( $obj->m_TABLE_NAME );
            
            if ( ! is_null( $obj->m_REFERENCED_TABLE_NAME ) ) {
                $obj_new->GetData( )->AddReferredTableName( $obj->m_REFERENCED_TABLE_NAME );
            }
            
            $this->InsertNode( $obj_new );
            
		} else {
		
            // if the referencing table does exist, then update its references
		
            if ( ! is_null( $obj->m_REFERENCED_TABLE_NAME ) ) {
                $obj_found->GetData( )->AddReferredTableName( $obj->m_REFERENCED_TABLE_NAME );
            }
		}
		
		// if the target table does not exist, then insert it in the tree
		
		if ( ! is_null( $obj->m_REFERENCED_TABLE_NAME ) ) {
		
            $obj_ref = $this->SearchByKey( $obj->m_REFERENCED_TABLE_NAME );
            if ( $obj_ref === false ) {            
                $obj_new = new cKeyColumnUsageTreeNode( $obj->m_REFERENCED_TABLE_NAME );
                $this->InsertNode( $obj_new );
            }
		}
		
	}
1292911
private function setRelationship(Vocal $record, $relationship, $class, $index)
    {
        // If we have an index we're dealing with a many relationship
        if ($index !== null)
        {
            $collection = ($this->{$relationship}) ? $this->{$relationship} : new Collection;
            $collection->put($index, $record);
            return $this->setRelation($relationship, $collection);
        }

        // belongsTo and morphTo become parent records via associate
        $model = $this->{$class}();

        if (method_exists($model, 'associate'))
        {
            return $model->associate($record)->forceSave();
        }
        else
        {
            return $this->setRelation($relationship, $record);
        }
    }
321670
public function belongsToMany(
        $entity,
        string $related,
        string $table = null,
        string $foreignKey = null,
        string $otherKey = null
    ): BelongsToMany {
        // Add the relation to the definition in map
        list(, $caller) = debug_backtrace(false);
        $relation = $caller['function'];
        $this->relatedClasses[$relation] = $related;

        $this->addManyRelation($relation);
        $this->addForeignRelation($relation);
        $this->addPivotRelation($relation);

        // First, we'll need to determine the foreign key and "other key" for the
        // relationship. Once we have determined the keys we'll make the query
        // instances as well as the relationship instances we need for this.
        $foreignKey = $foreignKey ?: $this->getForeignKey();

        $relatedMapper = Manager::getInstance()->mapper($related);

        $relatedMap = $relatedMapper->getEntityMap();

        $otherKey = $otherKey ?: $relatedMap->getForeignKey();

        // If no table name was provided, we can guess it by concatenating the two
        // models using underscores in alphabetical order. The two model names
        // are transformed to snake case from their default CamelCase also.
        if (is_null($table)) {
            $table = $this->joiningTable($relatedMap);
        }

        return new BelongsToMany($relatedMapper, $entity, $table, $foreignKey, $otherKey, $relation);
    }
310268
public function fillRecordWithRelations(Record $record)
    {
        foreach ($this->getWith() as $relation) {
            $relation->fillRecord($record);
        }

        return $record;
    }
101604
public function onRelationManageAdd()
    {
        $this->beforeAjax();

        $recordId = post('record_id');
        $sessionKey = $this->deferredBinding ? $this->relationGetSessionKey() : null;

        /*
         * Add
         */
        if ($this->viewMode == 'multi') {

            $checkedIds = $recordId ? [$recordId] : post('checked');

            if (is_array($checkedIds)) {
                /*
                 * Remove existing relations from the array
                 */
                $existingIds = $this->findExistingRelationIds($checkedIds);
                $checkedIds = array_diff($checkedIds, $existingIds);
                $foreignKeyName = $this->relationModel->getKeyName();

                $models = $this->relationModel->whereIn($foreignKeyName, $checkedIds)->get();
                foreach ($models as $model) {
                    $this->relationObject->add($model, $sessionKey);
                }
            }

        }
        /*
         * Link
         */
        elseif ($this->viewMode == 'single') {
            if ($recordId && ($model = $this->relationModel->find($recordId))) {

                $this->relationObject->add($model, $sessionKey);
                $this->viewWidget->setFormValues($model->attributes);

                /*
                 * Belongs to relations won't save when using add() so
                 * it should occur if the conditions are right.
                 */
                if (!$this->deferredBinding && $this->relationType == 'belongsTo') {
                    $parentModel = $this->relationObject->getParent();
                    if ($parentModel->exists) {
                        $parentModel->save();
                    }
                }

            }
        }

        return $this->relationRefresh();
    }
261995
public static function validateToOneRelation($relation, $relationship)
    {
        if (
            !is_null($relation)
            && !$relation instanceof ResourceEntityInterface
        ) {
            $type = is_object($relation)
                ? get_class($relation) : gettype($relation);
            throw new \Exception(sprintf(
                self::ERROR_NOT_RESOURCE_ENTITY, $relationship, $type
            ));
        }
    }
1285819
public static function buildRelationQuery($entity, Relation $relation) {
        $relQuery = "";
        $getid = "getId";
        if ($relation->getCardinality() == Relation::$manyToMany) {
            $m = "get" . $relation->getName();
            $relQuery .= "INSERT INTO " . $relation->getTable() . " (" . $relation->getLocalColumn() . ", " . $relation->getForeignColumn() . ") ";
            $relQuery .= "VALUES (:" . $relation->getLocalColumn() . ", :" . $relation->getForeignColumn() . ");";
        }
        if ($relation->getCardinality() == Relation::$oneToMany) {
            $relMapper = MapperBuilder::buildFromName($this->mapping, $relation->getEntity());
            $m = "get" . $relation->getName();
            foreach ($entity->$m() as $rel) {
                $setid = "set" . $relMapper->getNameForColumn($relation->getForeignColumn());
                $rel->$setid($entity->$getid());
                $relQuery .= $this->buildInsertQuery($rel);
            }
        }


        return $relQuery;
    }
1126517
public function populateJoinedRelations($model, array $row)
    {
        foreach ($row as $key => $value) {
            if (empty($this->join) || !is_array($value) || $model->hasAttribute($key)) {
                continue;
            }
            foreach ($this->join as $join) {
                $keys = array_keys($join);
                $name = array_shift($keys);
                $closure = array_shift($join);

                if (is_int($name)) {
                    $name = $closure;
                    $closure = null;
                }
                if ($name !== $key) {
                    continue;
                }
                if ($model->isRelationPopulated($name)) {
                    continue 2;
                }
                $records = [];
                $relation = $model->getRelation($name);
                $relationClass = $relation->modelClass;
                if ($closure !== null) {
                    call_user_func($closure, $relation);
                }
                $relation->prepare();

                if ($relation->multiple) {
                    foreach ($value as $item) {
                        $relatedModel = $relationClass::instantiate($item);
                        $relatedModelClass = get_class($relatedModel);
                        $relatedModelClass::populateRecord($relatedModel, $item);
                        $relation->populateJoinedRelations($relatedModel, $item);
                        $relation->addInverseRelation($relatedModel, $model);
                        $relatedModel->trigger(BaseActiveRecord::EVENT_AFTER_FIND);
                        if ($relation->indexBy !== null) {
                            $index = is_string($relation->indexBy)
                                ? $relatedModel[$relation->indexBy]
                                : call_user_func($relation->indexBy, $relatedModel);
                            $records[$index] = $relatedModel;
                        } else {
                            $records[] = $relatedModel;
                        }
                    }
                } else {
                    $relatedModel = $relationClass::instantiate($value);
                    $relatedModelClass = get_class($relatedModel);
                    $relatedModelClass::populateRecord($relatedModel, $value);
                    $relation->populateJoinedRelations($relatedModel, $value);
                    $relation->addInverseRelation($relatedModel, $model);
                    $relatedModel->trigger(BaseActiveRecord::EVENT_AFTER_FIND);
                    $records = $relatedModel;
                }

                $model->populateRelation($name, $records);
            }
        }
    }
1036793
protected function joinIntermediate(Model $parent, Relation $relation, $type)
    {
        if ($relation instanceof BelongsToMany) {
            $table = $relation->getTable();
            $fk = $relation->getQualifiedForeignPivotKeyName();
        } else {
            $table = $relation->getParent()->getTable();
            $fk = $relation->getQualifiedFirstKeyName();
        }

        $pk = $parent->getQualifiedKeyName();

        if (!$this->alreadyJoined($join = (new Join($this->query, $type, $table))->on($fk, '=', $pk))) {
            $this->query->joins[] = $join;
        }
    }
321865
public function saveChanges($primaryValue, Connection $connection, Collection $collection)
    {
        if ($collection->getEntityClass() !== $this->targetReflection->getClassName()) {
            throw new AssociationException(
                "Input collection should be type of "
                . $this->targetReflection->getClassName()
                . " but type of " . $collection->getEntityClass() . " given!"
            );
        }

        $changes = array_filter($collection->getChanges());
        if (empty($changes)) {
            return;
        }

        $sourceAdapter = $connection->getAdapter($this->sourceReflection->getAdapterName());
        $targetAdapter = $connection->getAdapter($this->targetReflection->getAdapterName());
        $mapper = $connection->getMapper();

        if (!$this->dominant) {
            $sourceAdapter = $targetAdapter;
        }

        // Unmap primary value
        $primaryValue = $mapper->unmapValue(
            $this->sourceReflection->getPrimaryProperty(),
            $primaryValue
        );

        $this->_saveAdd(
            $primaryValue,
            $sourceAdapter,
            $targetAdapter,
            $collection->getChanges(),
            $mapper
        );

        $this->_saveRemove(
            $primaryValue,
            $sourceAdapter,
            $targetAdapter,
            $collection->getChanges(),
            $mapper
        );
    }
1357676
def resolve_column(relation, column)
      node = relation.send(:relation).send(:arel_columns, [column]).first
      node = Arel::Nodes::SqlLiteral.new(node) if node.is_a?(String)
      relation.connection.visitor.accept(node, Arel::Collectors::SQLString.new).value
    end
285052
protected function insertBelongsToMany($recordName, Relation $relation, $columnValue)
    {
        $joinTable = $relation->getTable();
        $this->tables[] = $joinTable;
        $relatedRecords = explode(',', str_replace(', ', ',', $columnValue));

        foreach ($relatedRecords as $relatedRecord) {
            list($fields, $values) = $this->buildBelongsToManyRecord($recordName, $relation, $relatedRecord);
            $placeholders = rtrim(str_repeat('?, ', count($values)), ', ');
            $sql = "INSERT INTO $joinTable ($fields) VALUES ($placeholders)";
            $sth = $this->db->prepare($sql);
            $sth->execute($values);
        }
    }
1058161
public function belongsToMany($related, $table = null, $foreignKey = null, $otherKey = null, $relation = null)
    {
        // If no relationship name was passed, we will pull backtraces to get the
        // name of the calling function. We will use that function name as the
        // title of this relation since that is a great convention to apply.
        if (is_null($relation)) {
            $relation = $this->getBelongsToManyCaller();
        }

        $foreignKey = $foreignKey ?: $this->getCmsReferenceKeyForRelation($relation);
        $otherKey   = $otherKey   ?: $this->getCmsReferenceKeyForRelation($relation, true);

        if (is_null($table)) {
            $table = $this->getCmsJoiningTable();
        }

        $fieldId = $this->getCmsReferenceFieldId($relation);
        if (empty($fieldId)) {
            throw new InvalidArgumentException("No 'field' id configured for relation/reference: '{$relation}'!");
        }

        // originally, it was possible to just get the parent's BelongsToMany instance, but
        // to avoid problems when saving on the relationship, we need a specialized extension
        // of the relation class for the CMS.
        //$belongsToMany = parent::belongsToMany($related, $table, $foreignKey, $otherKey);

        /** @var Model $instance */
        $instance = new $related;

        $query = $instance->newQuery();

        $belongsToMany = new BelongsToMany($query, $this, $table, $foreignKey, $otherKey, $relation, $fieldId);

        // add constraints
        $belongsToMany->wherePivot(config('pxlcms.relations.references.keys.field', 'from_field_id'), $fieldId);

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

        $this->relations->add(
            new Relations\BelongsTo($this, $relatedModel, $foreignKey)
        );
    }
398280
protected function syncBelongsToManyRelation(
        \Illuminate\Database\Eloquent\Relations\BelongsToMany $relation,
        array $values
    ) {
        foreach ($values as $i => $value) {
            if (! array_key_exists($value, $this->getOptions()) && $this->isTaggable()) {
                $model = clone $this->getModelForOptions();
                $model->{$this->getDisplay()} = $value;
                $model->save();

                $values[$i] = $model->getKey();
            }
        }

        if (is_callable($callback = $this->getSyncCallback())) {
            $callbackModel = $this->getModel();
            $callback($values, $callbackModel);

            return;
        }

        $relation->sync($values);
    }
137705
public function saveIntoRelation(Relation $relation)
    {
        $ids = [];
        
        if ($values = $this->getValueArray()) {
            $ids = $this->getList()->filter($this->getIDField(), $values)->getIDList();
        }
        
        $relation->setByIDList($ids);
    }