| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306 | <?php namespace Laravel\Database\Eloquent;use Laravel\Database;use Laravel\Database\Eloquent\Relationships\Has_Many_And_Belongs_To;class Query {	/**	 * The model instance being queried.	 *	 * @var Model	 */	public $model;	/**	 * The fluent query builder for the query instance.	 *	 * @var Query	 */	public $table;	/**	 * The relationships that should be eagerly loaded by the query.	 *	 * @var array	 */	public $includes = array();	/**	 * The methods that should be returned from the fluent query builder.	 *	 * @var array	 */	public $passthru = array(		'lists', 'only', 'insert', 'insert_get_id', 'update', 'increment',		'decrement', 'count', 'min', 'max', 'avg', 'sum',	);	/**	 * Creat a new query instance for a model.	 *	 * @param  Model  $model	 * @return void	 */	public function __construct($model)	{		$this->model = ($model instanceof Model) ? $model : new $model;		$this->table = $this->table();	}	/**	 * Get the first model result for the query.	 *	 * @param  array  $columns	 * @return mixed	 */	public function first($columns = array('*'))	{		$results = $this->hydrate($this->model, $this->table->take(1)->get($columns));		return (count($results) > 0) ? head($results) : null;	}	/**	 * Get all of the model results for the query.	 *	 * @param  array  $columns	 * @param  bool   $keyed	 * @return array	 */	public function get($columns = array('*'), $keyed = true)	{		return $this->hydrate($this->model, $this->table->get($columns), $keyed);	}	/**	 * Get an array of paginated model results.	 *	 * @param  int        $per_page	 * @param  array      $columns	 * @return Paginator	 */	public function paginate($per_page = null, $columns = array('*'))	{		$per_page = $per_page ?: $this->model->per_page();		// First we'll grab the Paginator instance and get the results. Then we can		// feed those raw database results into the hydrate method to get models		// for the results, which we'll set on the paginator and return it.		$paginator = $this->table->paginate($per_page, $columns);		$paginator->results = $this->hydrate($this->model, $paginator->results);		return $paginator;	}	/**	 * Hydrate an array of models from the given results.	 *	 * @param  Model  $model	 * @param  array  $results	 * @param  bool   $keyed	 * @return array	 */	public function hydrate($model, $results, $keyed = true)	{		$class = get_class($model);		$models = array();		// We'll spin through the array of database results and hydrate a model		// for each one of the records. We will also set the "exists" flag to		// "true" so that the model will be updated when it is saved.		foreach ((array) $results as $result)		{			$result = (array) $result;			$new = new $class(array(), true);			// We need to set the attributes manually in case the accessible property is			// set on the array which will prevent the mass assignemnt of attributes if			// we were to pass them in using the constructor or fill methods.			foreach ($result as $key => $value)			{				$new->set_attribute($key, $value);			}			$new->original = $new->attributes;			// Typically, the resulting models are keyed by their primary key, but it			// may be useful to not do this in some circumstances such as when we			// are eager loading a *-to-* relationships which has duplicates.			if ($keyed)			{				$models[$result[$this->model->key()]] = $new;			}			else			{				$models[] = $new;			}		}		if (count($results) > 0)		{			foreach ($this->model_includes() as $relationship => $constraints)			{				// If the relationship is nested, we will skip laoding it here and let				// the load method parse and set the nested eager loads on the right				// relationship when it is getting ready to eager laod.				if (str_contains($relationship, '.'))				{					continue;				}				$this->load($models, $relationship, $constraints);			}		}		// The many to many relationships may have pivot table column on them		// so we will call the "clean" method on the relationship to remove		// any pivot columns that are on the model.		if ($this instanceof Relationships\Has_Many_And_Belongs_To)		{			$this->hydrate_pivot($models);		}		return $models;	}	/**	 * Hydrate an eagerly loaded relationship on the model results.	 *	 * @param  array       $results	 * @param  string      $relationship	 * @param  array|null  $constraints	 * @return void	 */	protected function load(&$results, $relationship, $constraints)	{		$query = $this->model->$relationship();		$query->model->includes = $this->nested_includes($relationship);		// We'll remove any of the where clauses from the relationship to give		// the relationship the opportunity to set the constraints for an		// eager relationship using a separate, specific method.		$query->table->reset_where();		$query->eagerly_constrain($results);		// Constraints may be specified in-line for the eager load by passing		// a Closure as the value portion of the eager load. We can use the		// query builder's nested query support to add the constraints.		if ( ! is_null($constraints))		{			$query->table->where_nested($constraints);		}		$query->initialize($results, $relationship);		// If we're eager loading a many-to-many relationship we will disable		// the primary key indexing on the hydration since there could be		// roles shared across users and we don't want to overwrite.		if ( ! $query instanceof Has_Many_And_Belongs_To)		{			$query->match($relationship, $results, $query->get());		}		else		{			$query->match($relationship, $results, $query->get(array('*'), false));		}	}	/**	 * Gather the nested includes for a given relationship.	 *	 * @param  string  $relationship	 * @return array	 */	protected function nested_includes($relationship)	{		$nested = array();		foreach ($this->model_includes() as $include => $constraints)		{			// To get the nested includes, we want to find any includes that begin			// the relationship and a dot, then we will strip off the leading			// nesting indicator and set the include in the array.			if (starts_with($include, $relationship.'.'))			{				$nested[substr($include, strlen($relationship.'.'))] = $constraints;			}		}		return $nested;	}	/**	 * Get the eagerly loaded relationships for the model.	 *	 * @return array	 */	protected function model_includes()	{		$includes = array();		foreach ($this->model->includes as $relationship => $constraints)		{			// When eager loading relationships, constraints may be set on the eager			// load definition; however, is none are set, we need to swap the key			// and the value of the array since there are no constraints.			if (is_numeric($relationship))			{				list($relationship, $constraints) = array($constraints, null);			}			$includes[$relationship] = $constraints;		}		return $includes;	}	/**	 * Get a fluent query builder for the model.	 *	 * @return Query	 */	protected function table()	{		return $this->connection()->table($this->model->table());	}	/**	 * Get the database connection for the model.	 *	 * @return Connection	 */	public function connection()	{		return Database::connection($this->model->connection());	}	/**	 * Handle dynamic method calls to the query.	 *	 * @param  string  $method	 * @param  array   $parameters	 * @return mixed	 */	public function __call($method, $parameters)	{		$result = call_user_func_array(array($this->table, $method), $parameters);		// Some methods may get their results straight from the fluent query		// builder, such as the aggregate methods. If the called method is		// one of these, we will return the result straight away.		if (in_array($method, $this->passthru))		{			return $result;		}		return $this;	}}
 |