query.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. <?php namespace Laravel\Database\Eloquent;
  2. use Laravel\Database;
  3. use Laravel\Database\Eloquent\Relationships\Has_Many_And_Belongs_To;
  4. class Query {
  5. /**
  6. * The model instance being queried.
  7. *
  8. * @var Model
  9. */
  10. public $model;
  11. /**
  12. * The fluent query builder for the query instance.
  13. *
  14. * @var Query
  15. */
  16. public $table;
  17. /**
  18. * The relationships that should be eagerly loaded by the query.
  19. *
  20. * @var array
  21. */
  22. public $includes = array();
  23. /**
  24. * The methods that should be returned from the fluent query builder.
  25. *
  26. * @var array
  27. */
  28. public $passthru = array(
  29. 'lists', 'only', 'insert', 'insert_get_id', 'update', 'increment',
  30. 'decrement', 'count', 'min', 'max', 'avg', 'sum',
  31. );
  32. /**
  33. * Creat a new query instance for a model.
  34. *
  35. * @param Model $model
  36. * @return void
  37. */
  38. public function __construct($model)
  39. {
  40. $this->model = ($model instanceof Model) ? $model : new $model;
  41. $this->table = $this->table();
  42. }
  43. /**
  44. * Get the first model result for the query.
  45. *
  46. * @param array $columns
  47. * @return mixed
  48. */
  49. public function first($columns = array('*'))
  50. {
  51. $results = $this->hydrate($this->model, $this->table->take(1)->get($columns));
  52. return (count($results) > 0) ? head($results) : null;
  53. }
  54. /**
  55. * Get all of the model results for the query.
  56. *
  57. * @param array $columns
  58. * @param bool $keyed
  59. * @return array
  60. */
  61. public function get($columns = array('*'), $keyed = true)
  62. {
  63. return $this->hydrate($this->model, $this->table->get($columns), $keyed);
  64. }
  65. /**
  66. * Get an array of paginated model results.
  67. *
  68. * @param int $per_page
  69. * @param array $columns
  70. * @return Paginator
  71. */
  72. public function paginate($per_page = null, $columns = array('*'))
  73. {
  74. $per_page = $per_page ?: $this->model->per_page();
  75. // First we'll grab the Paginator instance and get the results. Then we can
  76. // feed those raw database results into the hydrate method to get models
  77. // for the results, which we'll set on the paginator and return it.
  78. $paginator = $this->table->paginate($per_page, $columns);
  79. $paginator->results = $this->hydrate($this->model, $paginator->results);
  80. return $paginator;
  81. }
  82. /**
  83. * Hydrate an array of models from the given results.
  84. *
  85. * @param Model $model
  86. * @param array $results
  87. * @param bool $keyed
  88. * @return array
  89. */
  90. public function hydrate($model, $results, $keyed = true)
  91. {
  92. $class = get_class($model);
  93. $models = array();
  94. // We'll spin through the array of database results and hydrate a model
  95. // for each one of the records. We will also set the "exists" flag to
  96. // "true" so that the model will be updated when it is saved.
  97. foreach ((array) $results as $result)
  98. {
  99. $result = (array) $result;
  100. $new = new $class(array(), true);
  101. // We need to set the attributes manually in case the accessible property is
  102. // set on the array which will prevent the mass assignemnt of attributes if
  103. // we were to pass them in using the constructor or fill methods.
  104. foreach ($result as $key => $value)
  105. {
  106. $new->set_attribute($key, $value);
  107. }
  108. $new->original = $new->attributes;
  109. // Typically, the resulting models are keyed by their primary key, but it
  110. // may be useful to not do this in some circumstances such as when we
  111. // are eager loading a *-to-* relationships which has duplicates.
  112. if ($keyed)
  113. {
  114. $models[$result[$this->model->key()]] = $new;
  115. }
  116. else
  117. {
  118. $models[] = $new;
  119. }
  120. }
  121. if (count($results) > 0)
  122. {
  123. foreach ($this->model_includes() as $relationship => $constraints)
  124. {
  125. // If the relationship is nested, we will skip laoding it here and let
  126. // the load method parse and set the nested eager loads on the right
  127. // relationship when it is getting ready to eager laod.
  128. if (str_contains($relationship, '.'))
  129. {
  130. continue;
  131. }
  132. $this->load($models, $relationship, $constraints);
  133. }
  134. }
  135. // The many to many relationships may have pivot table column on them
  136. // so we will call the "clean" method on the relationship to remove
  137. // any pivot columns that are on the model.
  138. if ($this instanceof Relationships\Has_Many_And_Belongs_To)
  139. {
  140. $this->hydrate_pivot($models);
  141. }
  142. return $models;
  143. }
  144. /**
  145. * Hydrate an eagerly loaded relationship on the model results.
  146. *
  147. * @param array $results
  148. * @param string $relationship
  149. * @param array|null $constraints
  150. * @return void
  151. */
  152. protected function load(&$results, $relationship, $constraints)
  153. {
  154. $query = $this->model->$relationship();
  155. $query->model->includes = $this->nested_includes($relationship);
  156. // We'll remove any of the where clauses from the relationship to give
  157. // the relationship the opportunity to set the constraints for an
  158. // eager relationship using a separate, specific method.
  159. $query->table->reset_where();
  160. $query->eagerly_constrain($results);
  161. // Constraints may be specified in-line for the eager load by passing
  162. // a Closure as the value portion of the eager load. We can use the
  163. // query builder's nested query support to add the constraints.
  164. if ( ! is_null($constraints))
  165. {
  166. $query->table->where_nested($constraints);
  167. }
  168. $query->initialize($results, $relationship);
  169. // If we're eager loading a many-to-many relationship we will disable
  170. // the primary key indexing on the hydration since there could be
  171. // roles shared across users and we don't want to overwrite.
  172. if ( ! $query instanceof Has_Many_And_Belongs_To)
  173. {
  174. $query->match($relationship, $results, $query->get());
  175. }
  176. else
  177. {
  178. $query->match($relationship, $results, $query->get(array('*'), false));
  179. }
  180. }
  181. /**
  182. * Gather the nested includes for a given relationship.
  183. *
  184. * @param string $relationship
  185. * @return array
  186. */
  187. protected function nested_includes($relationship)
  188. {
  189. $nested = array();
  190. foreach ($this->model_includes() as $include => $constraints)
  191. {
  192. // To get the nested includes, we want to find any includes that begin
  193. // the relationship and a dot, then we will strip off the leading
  194. // nesting indicator and set the include in the array.
  195. if (starts_with($include, $relationship.'.'))
  196. {
  197. $nested[substr($include, strlen($relationship.'.'))] = $constraints;
  198. }
  199. }
  200. return $nested;
  201. }
  202. /**
  203. * Get the eagerly loaded relationships for the model.
  204. *
  205. * @return array
  206. */
  207. protected function model_includes()
  208. {
  209. $includes = array();
  210. foreach ($this->model->includes as $relationship => $constraints)
  211. {
  212. // When eager loading relationships, constraints may be set on the eager
  213. // load definition; however, is none are set, we need to swap the key
  214. // and the value of the array since there are no constraints.
  215. if (is_numeric($relationship))
  216. {
  217. list($relationship, $constraints) = array($constraints, null);
  218. }
  219. $includes[$relationship] = $constraints;
  220. }
  221. return $includes;
  222. }
  223. /**
  224. * Get a fluent query builder for the model.
  225. *
  226. * @return Query
  227. */
  228. protected function table()
  229. {
  230. return $this->connection()->table($this->model->table());
  231. }
  232. /**
  233. * Get the database connection for the model.
  234. *
  235. * @return Connection
  236. */
  237. public function connection()
  238. {
  239. return Database::connection($this->model->connection());
  240. }
  241. /**
  242. * Handle dynamic method calls to the query.
  243. *
  244. * @param string $method
  245. * @param array $parameters
  246. * @return mixed
  247. */
  248. public function __call($method, $parameters)
  249. {
  250. $result = call_user_func_array(array($this->table, $method), $parameters);
  251. // Some methods may get their results straight from the fluent query
  252. // builder, such as the aggregate methods. If the called method is
  253. // one of these, we will return the result straight away.
  254. if (in_array($method, $this->passthru))
  255. {
  256. return $result;
  257. }
  258. return $this;
  259. }
  260. }