@param Queryable $input
@param $relation
@param $name
@param $type
@param $value

@return Builder
541061
protected function filterRelationShipColumn(Queryable $input, $relation, $name, $type, $value)
    {
        $relatedTable = $relation->getRelated()->getTable();

        return $this->query->whereHas(
            $input->getRelation(),
            function ($query) use ($relatedTable, $name, $type, $value) {
                $query = $this->applyQueryElementByType($query, $relatedTable, $name, $type, $value);

                return $query;
            }
        );
    }
998652
protected function cascadeRelation(Relation $relation, array $input, Model $parent = null)
	{
		// Make a child repository for containing the cascaded relationship through saves
		$target_model_class = get_class($relation->getQuery()->getModel());
		$relation_repository = (new self)->setModelClass($target_model_class);

		switch (get_class($relation)) {
			case BelongsTo::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\BelongsTo $relation
				 */
				// For BelongsTo, simply associate by foreign key.
				// (We don't have to assume the parent model exists to do this.)
				$related = $relation_repository->setInput($input)->save();
				$relation->associate($related);
				break;
			case HasMany::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\HasMany $relation
				 */
				// The parent model "owns" child models; any not specified here should be deleted.
				$current_ids = $relation->pluck($this->getKeyName())->toArray();
				$new_ids = array_filter(array_column($input, $this->getKeyName()));
				$removed_ids = array_diff($current_ids, $new_ids);
				if ( !empty($removed_ids)) {
					$relation->whereIn($this->getKeyName(), $removed_ids)->delete();
				}

				// Set foreign keys on the children from the parent, and save.
				foreach ($input as $sub_input) {
					$sub_input[$this->getRelationsForeignKeyName($relation)] = $parent->{$this->getKeyName()};
					$relation_repository->setInput($sub_input)->save();
				}
				break;
			case HasOne::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\HasOne $relation
				 */
				// The parent model "owns" the child model; if we have a new and/or different
				// existing child model, delete the old one.
				$current = $relation->getResults();
				if ( !is_null($current)
					&& ( !isset($input[$this->getKeyName()]) || $current->{$this->getKeyName()} !== intval($input[$this->getKeyName()]))
				) {
					$relation->delete();
				}

				// Set foreign key on the child from the parent, and save.
				$input[$this->getRelationsForeignKeyName($relation)] = $parent->{$this->getKeyName()};
				$relation_repository->setInput($input)->save();
				break;
			case BelongsToMany::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\BelongsToMany $relation
				 */
				// Find all the IDs to sync.
				$ids = [];

				foreach ($input as $sub_input) {
					$id = $relation_repository->setInput($sub_input)->save()->{$this->getKeyName()};

					// If we were passed pivot data, pass it through accordingly.
					if (isset($sub_input['pivot'])) {
						$ids[$id] = (array)$sub_input['pivot'];
					} else {
						$ids[] = $id;
					}
				}

				// Sync to save pivot table and optional extra data.
				$relation->sync($ids);
				break;
		}
	}
65563
public function input($type, $name, $value = null)
    {
        $value = $this->inputs ? $this->inputs->get($name, $value) : $value;
        $form  = (new Input($type, $name))->value($value);
        return $this->setClass($form);
    }
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;
        }
    }
599680
public function morphMany(
        $entity,
        string $related,
        string $name,
        string $type = null,
        string $id = null,
        string $localKey = null
    ): MorphMany {
        // Here we will gather up the morph type and ID for the relationship so that we
        // can properly query the intermediate table of a relation. Finally, we will
        // get the table and create the relationship instances for the developers.
        list($type, $id) = $this->getMorphs($name, $type, $id);

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

        $table = $relatedMapper->getEntityMap()->getTable();

        $localKey = $localKey ?: $this->getKeyName();

        // 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);

        return new MorphMany($relatedMapper, $entity, /*$table.'.'.*/$type, /*$table.'.'.*/$id, $localKey);
    }
29748
public function scopeHasAttribute(Builder $query, string $key, $value): Builder
    {
        return $query->whereHas($key, function (Builder $query) use ($value) {
            $query->where('content', $value)->where('entity_type', get_class($this));
        });
    }
991436
public function postUpdate($input)
	{
		$baseModel = $this->getAdmin()->getModel();
		$baseModel = $baseModel::find($this->getAdmin()->getFormBuilder()->getIdentifier());

		$morphType = $baseModel->{$this->getName()}()->getMorphType();
		$morphType = str_replace(sprintf('%s.', $this->getName()), '', $morphType);

		$foreignKey = $baseModel->{$this->getName()}()->getForeignKey();
		$foreignKey = str_replace(sprintf('%s.', $this->getName()), '', $foreignKey);

		// remove old polymorphic relations
		foreach ($baseModel->{$this->getName()} as $item) {
			$item->update([
				$foreignKey => 0,
				$morphType  => '',
			]);
		}

		// update new item with polymorphic relation
		$baseModel->{$this->getName()}()
			->getRelated()
			->where($items->getKeyName(), $input[$this->getName()])
			->update([
				$foreignKey => $this->getAdmin()->getFormBuilder()->getIdentifier(),
				$morphType  => get_class($baseModel),
			]);
	}
548844
public function addRel($relation, $value)
        {
            if (is_string($relation)) {
                $this->_rel[$relation] = $value;
            }

            return $this;
        }
1314563
public function scopeWhereExtensionAttribute(Builder $query, $type, $key, $value)
    {
        // We do this for querying, searching and sorting with source attributes
        $this->setNodeTypeName($type);

        return $query->whereHas('nodeSourceExtensions', function (Builder $query) use ($key, $value)
        {
            $query->where(source_table_name($this->getNodeTypeName()) . '.' . $key, $value);
        });
    }
1273814
private function addRelationQuery($type, $value)
    {
        $this->prepareRelationFilter($type);
        $this->filters[$type][] = $value;
        return $this;
    }
761040
public static function where($column, $relation, $value)
    {
        $self = self::instance();
        $key = $self->_keyName;
        $data = \Query::from($self->_table)->select($key)->where($column, $relation, $value)->get();
        $rows = [];

        if (!is_null($data)) {
            foreach ($data as $item) {
                $rows[] = self::instance($item->$key);
            }
        }

        return $rows;
    }
1113277
public function related($relation, $column, $operator = null, $value = null, $boolean = 'and')
    {
        if ($column instanceof \Closure) {
            return $this->addRelated($relation, $column);
        }

        // If there is no value it is a where = ? query and we set the appropriate params
        if ($value === null) {
            $value = $operator;
            $operator = '=';
        }

        return $this->addRelated($relation, function ($query) use ($column, $operator, $value, $boolean) {
            return $query->where($column, $operator, $value, $boolean);
        });
    }
1093066
protected function build_where($rules,$relation=false){
		$sql=array();
		for ($i=0; $i < sizeof($rules); $i++)
			if (is_string($rules[$i]))
				array_push($sql,"(".$rules[$i].")");
			else {
				$filtervalue = $rules[$i]["value"];
				$filteroperation = $rules[$i]["operation"];
				if ($filtervalue!=""){
					if (!$filteroperation)
						array_push($sql,$this->escape_name($rules[$i]["name"])." LIKE '%".$this->escape($filtervalue)."%'");
					else {
						if ($filteroperation != "IN") 
							$filtervalue = "'".$this->escape($filtervalue)."'";

						array_push($sql,$this->escape_name($rules[$i]["name"])." ".$filteroperation." ".$filtervalue);
					}
				}
			}

		if ($relation !== false && $relation !== ""){
			$relsql = $this->escape_name($this->config->relation_id["db_name"])." = '".$this->escape($relation)."'";
			if ($relation == "0")
				$relsql = "( ".$relsql." OR ".$this->escape_name($this->config->relation_id["db_name"])." IS NULL )";

			array_push($sql,$relsql);
		}
		return implode(" AND ",$sql);
	}
234071
private function applyNestedFilter(Builder $query, array $fields, $operator, $value, $or = false)
    {
        $relation_name = implode('.', array_slice($fields, 0, count($fields) - 1));
        $relation_field = end($fields);
        if ($relation_name[0] == '!') {
            $relation_name = substr($relation_name, 1, strlen($relation_name));

            $that = $this;

            return $query->whereHas($relation_name, function ($query) use ($relation_field, $operator, $value, $that, $or) {
                $query = $that->applyWhereClause($query, $relation_field, $operator, $value, $or);
            }, '=', 0);
        }

        $that = $this;

        return $query->whereHas($relation_name, function ($query) use ($relation_field, $operator, $value, $that, $or) {
            $query = $that->applyWhereClause($query, $relation_field, $operator, $value, $or);
        });
    }
785617
public function getParent ($relationIdentifier, $id, $inputQuery = null)
		{
			$relation = $this->getRelation($relationIdentifier);

			if (! $relation) {
				throw new RelationException('Invalid relation `' . $relationIdentifier);
			}

			if ($relation instanceof ManyToOne && $relation instanceof OneToOne) {
				throw new RelationException('Invalid relation type `' . $relation['type'] . '`');
			}

			$row = $this->getRow($id);

			$query = $this->database->createQuery()
				->whereEqual($relation->getKey(), $row[$relation->getRelatedKey()])
				->composeWith($inputQuery);

			return $relation->getRelatedTableObject()->getRows($query)->fetchRow();
		}
353808
private function hydrateRelation($entity, $name, $value)
    {
        $relationClass = $this->em
            ->getClassMetadata(get_class($entity))
            ->getAssociationMapping($name)["targetEntity"]
        ;

        $relation = $entity->{"get".Inflector::camelize($name)}();
        if(in_array('id', array_keys($value))) {
            $relation = $this->em->getRepository($relationClass)->find($value['id']);
            unset($value['id']);
        } elseif(empty($relation)) {
            $relation = new $relationClass;
        }

        return $this->hydrate($relation, $value);
    }
826948
public function lazyLoad($instance, $relation_name)
    {
        if (($relation = $this->get($instance, $relation_name)) === false) {
            throw new InvalidValueException($relation);
        }

        $type = $relation->type;
        $referenceModel = $relation->referenceModel;
        $valueField = $relation->valueField;
        if ($type === Relation::TYPE_HAS_ONE) {
            return $referenceModel::query()->whereEq($relation->keyField, $instance->$valueField)->setFetchType(false);
        } elseif ($type === Relation::TYPE_BELONGS_TO) {
            return $referenceModel::query()->whereEq($relation->keyField, $instance->$valueField)->setFetchType(false);
        } elseif ($type === Relation::TYPE_HAS_MANY) {
            return $referenceModel::query()->whereEq($relation->keyField, $instance->$valueField)->setFetchType(true);
        } elseif ($type === Relation::TYPE_HAS_MANY_TO_MANY) {
            $ids = $instance::values($relation->keyField, [$valueField => $instance->$valueField]);
            /** @var \ManaPHP\Model $referenceInstance */
            $referenceInstance = is_string($referenceModel) ? new $referenceModel : $referenceModel;
            return $referenceModel::query()->whereIn($referenceInstance->getPrimaryKey(), $ids)->setFetchType(true);
        } elseif ($type === Relation::TYPE_HAS_MANY_VIA) {
            $via = $relation->keyField;
            /** @var \ManaPHP\Model $reference */
            $reference = new $referenceModel();
            $ids = $via::values($reference->getPrimaryKey(), [$valueField => $instance->$valueField]);
            return $referenceModel::query()->whereIn($reference->getPrimaryKey(), $ids)->setFetchType(true);
        } else {
            throw  new NotSupportedException(['unknown relation type: :type', 'type' => $type]);
        }
    }