Returns a BelongsTo relation.

@param  string                                     $model      Related model
@param  string|null                                $foreignKey Foreign key name
@return \mako\database\midgard\relations\BelongsTo
182979
protected function belongsTo(string $model, ?string $foreignKey = null): BelongsTo
	{
		$related = new $model;

		return new BelongsTo($related->getConnection(), $this, $related, $foreignKey);
	}
848538
public function getForeignKey()
    {
        if ($this->foreignKey !== null) {
            return $this->foreignKey;
        }
        $this->init();
        switch ($this->type) {
            case self::HAS_MANY:
            case self::HAS_ONE:
                return $this->owner->getTableName() . '_' . $this->owner->getPrimaryKey();
            case self::BELONGS_TO:
                return $this->foreign->getPrimaryKey();
            default:
                throw new \Exception(sprintf("Relation type '%s' is not supported.", $this->type));
        }
    }
376461
public function hasMany($name, $foreignKey, $modelName = null)
    {
        $this->addAssociation('hasMany', $name, $foreignKey, $modelName);
        return $this;
    }
765650
public function belongsTo($alias, $class, $foreignKey = null, Closure $conditions = null) {
        $relation = (new ManyToOne($alias, $class))
            ->setPrimaryForeignKey($foreignKey);

        if ($conditions) {
            $relation->setConditions($conditions);
        }

        return $this->addRelation($relation);
    }
1337819
public function foreignMany($related, $foreignKey = null, $localKey = null)
    {
        $instance = new $related;

        $foreignKey = $foreignKey ?: Str::snake(class_basename($this)).'_id';

        $localKey = $localKey ?: '_id';

        return new ForeignMany($this, $instance->query(['*']), $foreignKey, $localKey);
    }
1194526
protected function _relationship($modelName, $relationship, $foreignKey=null, $localKey=null)
    {
        /**
         * PSR-4 support check
         * 
         * @see https://github.com/yidas/codeigniter-psr4-autoload
         */
        if (strpos($modelName, "\\") !== false ) {
            
            $model = new $modelName;

        } else {
            // Original CodeIgniter 3 model loader
            get_instance()->load->model($modelName);
            $model = $this->$modelName;
        }

        $libClass = __CLASS__;
        
        // Check if is using same library
        if (!is_subclass_of($model, $libClass)) {
            throw new Exception("Model `{$modelName}` does not extend {$libClass}", 500);
        }

        // Keys
        $foreignKey = ($foreignKey) ? $foreignKey : $this->primaryKey;
        $localKey = ($localKey) ? $localKey : $this->primaryKey; 

        $query = $model->find()
            ->where($foreignKey, $this->$localKey);

        // Inject Model name into query builder for ORM relationships
        $query->modelName = $modelName;
        // Inject relationship type into query builder for ORM relationships
        $query->relationship = $relationship;

        return $query;
    }
709037
public function belongsToThrough($related, $through, $localKey = null, $prefix = '', $foreignKeyLookup = [])
    {
        /** @var \Illuminate\Database\Eloquent\Model $relatedInstance */
        $relatedInstance = new $related;
        $throughParents = [];
        $foreignKeys = [];

        foreach ((array) $through as $model) {
            $foreignKey = null;

            if (is_array($model)) {
                $foreignKey = $model[1];

                $model = $model[0];
            }

            /** @var \Illuminate\Database\Eloquent\Model $instance */
            $instance = new $model;

            if ($foreignKey) {
                $foreignKeys[$instance->getTable()] = $foreignKey;
            }

            $throughParents[] = $instance;
        }

        foreach ($foreignKeyLookup as $model => $foreignKey) {
            $instance = new $model;

            if ($foreignKey) {
                $foreignKeys[$instance->getTable()] = $foreignKey;
            }
        }

        return $this->newBelongsToThrough($relatedInstance->newQuery(), $this, $throughParents, $localKey, $prefix, $foreignKeys);
    }
1279723
public function belongs($name, $foreignKeyOrCallback = null, $callback = null, $storeKey = null)
    {
        $foreignKey = null;
        if (func_num_args() < 4 && is_callable($foreignKeyOrCallback)) {
            $storeKey = $callback;
            $callback = $foreignKeyOrCallback;
        } else {
            $foreignKey = $foreignKeyOrCallback;
        }
        $foreignKey = $foreignKey ? : $this->rows
            ->getTable()
            ->getStructure()
            ->foreignKey($name, $this->getRows()->getTable()->getTableName());
        $relations = $this->getRows()->loadBelongRelations($name, $foreignKey, $callback, $storeKey);
        $this->loadedRelations[] = [
            $storeKey ? : $name, 'belongs', $foreignKey
        ];
        return $relations->find($this->$foreignKey);
    }
920263
public static function get(array $options)
    {
        if (!array_key_exists('type', $options) || !array_key_exists('params', $options) || !array_key_exists('name', $options)) {
			
			if(count($options) >= 3) {
				$values = array_values($options);
				$field = isset($values[3]) ? $values[3] : null;
				return new ForeignRelationship(
					$values[1],
					$values[2],
					$values[0],
					$field
				);				
			}
			
            return null;
        }
		
		$field = array_key_exists('field', $options) ? $options['field'] : null;

        return new ForeignRelationship(
            $options['type'],
            $options['params'],
            $options['name'],
            $field
        );
    }
184801
protected function getRelInstance($model=null, $relConf=null, $key='', $pushFilter=false) {
		if (!$model && !$relConf)
			trigger_error(self::E_MISSING_REL_CONF,E_USER_ERROR);
		$relConf = $model ? $model::resolveConfiguration() : $relConf;
		$relName = ($model?:'Cortex').'\\'.$relConf['db']->uuid().
			'\\'.$relConf['table'].'\\'.$key;
		if (\Registry::exists($relName)) {
			$rel = \Registry::get($relName);
			$rel->reset();
		} else {
			$rel = $model ? new $model : new Cortex($relConf['db'], $relConf['table']);
			if (!$rel instanceof Cortex)
				trigger_error(self::E_WRONG_RELATION_CLASS,E_USER_ERROR);
			\Registry::set($relName, $rel);
		}
		// restrict fields of related mapper
		if(!empty($key) && isset($this->relWhitelist[$key])) {
			if (isset($this->relWhitelist[$key][0]))
				$rel->fields($this->relWhitelist[$key][0],false);
			if (isset($this->relWhitelist[$key][1]))
				$rel->fields($this->relWhitelist[$key][1],true);
		}
		if ($pushFilter && !empty($key)) {
			if (isset($this->relFilter[$key.'.'])) {
				foreach($this->relFilter[$key.'.'] as $fkey=>$conf)
					$rel->filter($fkey,$conf[0],$conf[1]);
			}
			if (isset($this->hasCond[$key.'.'])) {
				foreach($this->hasCond[$key.'.'] as $fkey=>$conf)
					$rel->has($fkey,$conf[0],$conf[1]);
			}
		}
		return $rel;
	}
1270910
public function join(
        $foreignTable,
        $leftField = null,
        $joinKind = null,
        $joinAlias = null,
        $relation = null,
        $behaviour = 'cascade'
    ) {
        list($rightTable, $rightField) = explode('.', $foreignTable, 2);
        if (is_null($rightField)) {
            $rightField = 'id';
        }
        $referenceType = ($rightField === 'id') ? 'hasOne' : 'hasMany';
        if ($referenceType === 'hasMany') {
            throw $this->exception('has many join isn\'t supported');
        }
        $leftTable = $this->table;

        $joinAlias = $this->_unique($this->relations, $joinAlias);
        /** @type Field_SQL_Relation $field */
        $field = $this->add($this->defaultSQLRelationFieldClass);
        $field->setLeftTable($relation ?: $leftTable)
            ->setLeftField($leftField)
            ->setRightTable($rightTable)
            ->setRightField($rightField)
            ->setJoinKind($joinKind)
            ->setJoinAlias($joinAlias)
            ->setModel($this);

        $field->referenceType = $referenceType;
        $field->setBehaviour($behaviour);

        $this->relations[$joinAlias] = $field;

        return $field;
    }
1374280
public function on($foreignKey, $key = null) {
        if (is_array($foreignKey)) {
            $this->_conditions = array_replace($this->_conditions, $foreignKey);
        } else {
            $this->_conditions[$foreignKey] = $key;
        }

        return $this;
    }
1142529
public function belongsTo($name, $foreignKey, $modelName = null)
    {
        $this->addAssociation('belongsTo', $name, $foreignKey, $modelName);
        return $this;
    }
505747
public function getForeignKey()
    {
        if (is_null($this->foreignKey)) {
            $name = $this->getEntityDescriptor()->getTableName();
            $this->foreignKey = "{$this->normalizeFieldName($name)}_id";
        }
        return $this->foreignKey;
    }
1328710
protected function getRelationshipMethod(ForeignRelationship $relation)
    {
        $stub = $this->getStubContent('model-relation');

        $this->replaceRelationName($stub, $relation->name)
            ->replaceRelationType($stub, $relation->getType())
            ->replaceRelationParams($stub, $this->turnRelationArgumentToString($relation->parameters));

        return $stub;
    }
1041304
public function setModel($model, $foreignKey, $foreignKeyIds)
    {
        $this->model = $model;
        $this->foreignKey = $foreignKey;
        $this->foreignKeyIds = array_wrap($foreignKeyIds);

        $this->message = "Integrity constraint violation [{$model}] where $foreignKey in (".implode(', ', $foreignKeyIds).')';

        return $this;
    }
1241537
protected function has_many( $model, $foreign_key = null, $local_key = null )
	{
		return new Model_Relation_HasMany( $this, $model, $foreign_key, $local_key );
	}