Order query by mapped attribute.

@param  \Sofa\Eloquence\Builder $query
@param  \Sofa\Hookable\Contracts\ArgumentBag $args
@param  string $table
@param  string $column
@param  string $target
@return \Sofa\Eloquence\Builder
425794
protected function orderByMapped(Builder $query, ArgumentBag $args, $table, $column, $target)
    {
        $query->with($target)->getQuery()->orderBy("{$table}.{$column}", $args->get('direction'));

        return $query;
    }
832531
public function insert($query, $args = array())
    {
        if ($this->exec($query, $args)) {
            return $this->getLastInsertId();
        }
        return false;
    }
470543
protected function orderData(Builder $query, Request $request, array $availableFields): Builder
    {
        $sortBy = $request->input('sort_by');
        $sortOrder = $request->input('sort_order');
        $modelPrefix = $this->model()::getTableName() . '.';

        if (in_array($sortBy, $availableFields)) {
            if (in_array(strtolower($sortOrder), ['asc', 'desc'])) {
                return $query->orderBy($modelPrefix . $sortBy, $sortOrder);
            }
        }

        return $query->orderBy($modelPrefix . 'created_at', 'desc');
    }
660679
public function apply($query, $column, $direction = 'asc')
    {
        $direction = $direction === 'desc' ? 'desc' : 'asc';

        $modelTable = $query->getModel()->getTable();
        $modelKey   = $query->getModel()->getKeyName();

        $query->orderBy("{$modelTable}.{$modelKey}", $direction);

        return $query;
    }
1301724
protected function mappedSelect(Builder $query, ArgumentBag $args)
    {
        $columns = $args->get('columns');

        foreach ($columns as $key => $column) {
            list($column, $as) = $this->extractColumnAlias($column);

            // Each mapped column will be selected appropriately. If it's alias
            // then prefix it with current table and use original field name
            // otherwise join required mapped tables and select the field.
            if ($this->hasMapping($column)) {
                $mapping = $this->getMappingForAttribute($column);

                if ($this->relationMapping($mapping)) {
                    list($target, $mapped) = $this->parseMappedColumn($mapping);

                    $table = $this->joinMapped($query, $target);
                } else {
                    list($table, $mapped) = [$this->getTable(), $mapping];
                }

                $columns[$key] = "{$table}.{$mapped}";

                if ($as !== $column) {
                    $columns[$key] .= " as {$as}";
                }

            // For non mapped columns present on this table we will simply
            // add the prefix, in order to avoid any column collisions,
            // that are likely to happen when we are joining tables.
            } elseif ($this->hasColumn($column)) {
                $columns[$key] = "{$this->getTable()}.{$column}";
            }
        }

        $args->set('columns', $columns);
    }
133727
protected function mappedJoinQuery($query, $method, ArgumentBag $args, $target, $column)
    {
        $table = $this->joinMapped($query, $target);

        // For aggregates we need the actual function name
        // so it can be called directly on the builder.
        $method = $args->get('function') ?: $method;

        return (in_array($method, ['orderBy', 'lists', 'pluck']))
            ? $this->{"{$method}Mapped"}($query, $args, $table, $column, $target)
            : $this->mappedSingleResult($query, $method, "{$table}.{$column}");
    }
97169
public function getRelationExistenceQueryForSelfRelation(Builder $query, Builder $parentQuery, $columns = ['*'])
    {
        $query->from($query->getModel()->getTable().' as '.$hash = $this->getRelationCountHash());

        $query->join($this->throughParent->getTable(), $this->getQualifiedParentKeyName(), '=', $hash.'.'.$this->secondKey);

        if ($this->throughParentSoftDeletes()) {
            $query->whereNull($this->throughParent->getQualifiedDeletedAtColumn());
        }

        $query->getModel()->setTable($hash);

        return $query->select($columns)->whereColumn(
            $parentQuery->getQuery()->from.'.'.$this->localKey, '=', $this->getQualifiedFirstKeyName()
        );
    }
927646
public function genUnionBindValues (&$query, $args)
	{
		
		foreach ($args as $key => $arg)
		{

			if (isset ($arg['where']) && is_array ($arg['where']))
			{
				$this->genBindValues ($query, $arg['where']);
			}
			
			if (isset ($arg['having']) && is_array ($arg['having']))
			{
				$this->genBindValues ($query, $arg['having']);
			}

		}
	}
523167
public function getRelationQuery(Builder $query, Builder $parent, $columns = ['*'])
	{
		if ($parent->getQuery()->from == $query->getQuery()->from) {
			return $this->getRelationQueryForSelfJoin($query, $parent, $columns);
		}

		$this->setJoin($query);

		return parent::getRelationQuery($query, $parent, $columns);
	}
517375
public function apply($query, $column, $direction = 'asc')
    {
        // Determine the best strategy to use for the column
        // (which may not even be a column on the model's own table)

        $strategy = $this->determineStrategy($query->getModel(), $column);

        if ($strategy) {

            $instance = app($strategy);

            if ( ! ($instance instanceof SortStrategyInterface)) {
                throw new UnexpectedValueException("{$strategy} is not a sort strategy");
            }

            $instance->apply($query, $column, $direction);
        }

        return $query;
    }
1091945
public static function ExecuteQuery ($query, array $conditions = [], array $values = [], array $options = []) {
		$options += $options + static::GetDefaultOptions();
		return DBI::ExecuteQuery($query, $conditions, $values, $options);
	}
671701
protected function pluckMapped(Builder $query, ArgumentBag $args, $table, $column)
    {
        $query->select("{$table}.{$column}");

        if (!is_null($args->get('key'))) {
            $this->mappedSelectListsKey($query, $args->get('key'));
        }

        $args->set('column', $column);

        return $query->callParent('pluck', $args->all());
    }
822019
private static function executeQuery($db, $method, array $args)
    {
        self::$query_count++;
        self::debugStart(current($args)); // sql is always the first arg
        $ret = call_user_func_array(array($db, $method), $args);
        self::debugEnd();

        if (MDB2::isError($ret)) {
            throw new SwatDBException($ret);
        }

        return $ret;
    }
382569
private function queryOrderBuilder($query, array $sortParameters)
    {
        $model = $this;

        list($column, $direction) = $this->parseParameters($sortParameters);

        if (is_null($column)) {
            return $query;
        }

        $explodeResult = SortableLink::explodeSortParameter($column);
        if ( ! empty($explodeResult)) {
            $relationName = $explodeResult[0];
            $column       = $explodeResult[1];

            try {
                $relation = $query->getRelation($relationName);
                $query    = $this->queryJoinBuilder($query, $relation);
            } catch (BadMethodCallException $e) {
                throw new ColumnSortableException($relationName, 1, $e);
            } catch (\Exception $e) {
                throw new ColumnSortableException($relationName, 2, $e);
            }

            $model = $relation->getRelated();
        }

        if (method_exists($model, camel_case($column).'Sortable')) {
            return call_user_func_array([$model, camel_case($column).'Sortable'], [$query, $direction]);
        }

        if (isset($model->sortableAs) && in_array($column, $model->sortableAs)) {
            $query = $query->orderBy($column, $direction);
        } elseif ($this->columnExists($model, $column)) {
            $column = $model->getTable().'.'.$column;
            $query  = $query->orderBy($column, $direction);
        }

        return $query;
    }
1207435
protected function compileFrom(Builder $query, $table)
    {
        $from = parent::compileFrom($query, $table);

        if (is_string($query->lock)) {
            return $from.' '.$query->lock;
        }

        if (! is_null($query->lock)) {
            return $from.' with(rowlock,'.($query->lock ? 'updlock,' : '').'holdlock)';
        }

        return $from;
    }
795265
public function scopeOrderByDislikesCount(Builder $query, $direction = 'desc')
    {
        return app(LikeableServiceContract::class)
            ->scopeOrderByLikesCount($query, LikeType::DISLIKE, $direction);
    }
881009
protected function applySortingToQueryBuilder($query, $source, $direction = 'asc', $strategy = null)
    {
        $source = $source ?: $query->getModel()->getKeyName();

        // Prepare the sorting strategy
        if (null === $strategy) {
            $strategy = config('cms-models.meta-references.sort-strategy');
        }

        if ( ! $strategy) return $this;


        $strategyInstance = new $strategy;

        if ( ! ($strategyInstance instanceof SortStrategyInterface)) {
            throw new UnexpectedValueException("{$strategy} is not a sort strategy");
        }

        // Explode combined source keys and apply the strategy for each part
        foreach (explode(',', $source) as $sourcePart) {

            $query = $strategyInstance->apply($query, $sourcePart, $direction);
        }

        return $this;
    }