public function applyNestedJoins(Builder $query, array $relations, Model $instance, $field, $direction = 'asc')
	{
		$base_table = $instance->getTable();

		// The current working relation
		$relation = $relations[0];

		// Current working table
		$table = Str::plural($relation);
		$singular = Str::singular($relation);
		$class = get_class($instance);

		// If the relation exists, determine which type (singular, multiple)
		if ($this->isRelation($instance, $singular, $class)) {
			$related = $instance->$singular();
		} elseif ($this->isRelation($instance, $relation, $class)) {
			$related = $instance->$relation();
		} else {
			// This relation does not exist
			return;
		}

		$foreign_key = $related->getForeignKey();

		// Join tables differently depending on relationship type
		switch (get_class($related)) {
			case BelongsToMany::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\BelongsToMany $related
				 */
				$base_table_key = $instance->getKeyName();
				$relation_primary_key = $related->getModel()->getKeyName();

				// Join through the pivot table
				$query->join($related->getTable(), "$base_table.$base_table_key", '=', $foreign_key);
				$query->join($table, $related->getOtherKey(), '=', "$relation.$relation_primary_key");
				break;
			case HasMany::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\HasMany $related
				 */
				$base_table_key = $instance->getKeyName();

				// Join child's table
				$query->join($table, "$base_table.$base_table_key", '=', $foreign_key);
				break;
			case BelongsTo::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\BelongsTo $related
				 */
				$relation_key = $related->getOtherKey();

				// Join related's table on the base table's foreign key
				$query->join($table, "$base_table.$foreign_key", '=', "$table.$relation_key");
				break;
			case HasOne::class:
				/**
				 * @var \Illuminate\Database\Eloquent\Relations\HasOne $related
				 */
				$parent_key = $instance->getKeyName();

				// Join related's table on the base table's foreign key
				$query->join($table, "$base_table.$parent_key", '=', "$foreign_key");
				break;
		}

		// @todo is it necessary to allow nested relationships further than the first/second degrees?
		array_shift($relations);

		if (count($relations) >= 1) {
			$this->applyNestedJoins($query, $relations, $related->getModel(), $field, $direction);
		} else {
			$query->orderBy("$table.$field", $direction);
		}
	}