eloquent.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. <?php namespace System\DB;
  2. use System\Str;
  3. use System\Inflector;
  4. abstract class Eloquent {
  5. /**
  6. * Indicates if the model exists in the database.
  7. *
  8. * @var bool
  9. */
  10. public $exists = false;
  11. /**
  12. * The model's attributes.
  13. *
  14. * Typically, a model has an attribute for each column on the table.
  15. *
  16. * @var array
  17. */
  18. public $attributes = array();
  19. /**
  20. * The model's dirty attributes.
  21. *
  22. * @var array
  23. */
  24. public $dirty = array();
  25. /**
  26. * The model's ignored attributes.
  27. *
  28. * Ignored attributes will not be saved to the database, and are
  29. * primarily used to hold relationships.
  30. *
  31. * @var array
  32. */
  33. public $ignore = array();
  34. /**
  35. * The relationships that should be eagerly loaded.
  36. *
  37. * @var array
  38. */
  39. public $includes = array();
  40. /**
  41. * The relationship type the model is currently resolving.
  42. *
  43. * @var string
  44. */
  45. public $relating;
  46. /**
  47. * The foreign key of the "relating" relationship.
  48. *
  49. * @var string
  50. */
  51. public $relating_key;
  52. /**
  53. * The table name of the model being resolved.
  54. *
  55. * This is used during many-to-many eager loading.
  56. *
  57. * @var string
  58. */
  59. public $relating_table;
  60. /**
  61. * The model query instance.
  62. *
  63. * @var Query
  64. */
  65. public $query;
  66. /**
  67. * Create a new Eloquent model instance.
  68. *
  69. * @param array $attributes
  70. * @return void
  71. */
  72. public function __construct($attributes = array())
  73. {
  74. foreach ($attributes as $key => $value)
  75. {
  76. $this->$key = $value;
  77. }
  78. }
  79. /**
  80. * Get the table name for a model.
  81. *
  82. * @param string $class
  83. * @return string
  84. */
  85. public static function table($class)
  86. {
  87. if (property_exists($class, 'table'))
  88. {
  89. return $class::$table;
  90. }
  91. return Str::lower(Inflector::plural($class));
  92. }
  93. /**
  94. * Factory for creating new Eloquent model instances.
  95. *
  96. * @param string $class
  97. * @return object
  98. */
  99. public static function make($class)
  100. {
  101. $model = new $class;
  102. // -----------------------------------------------------
  103. // Since this method is only used for instantiating
  104. // models for querying purposes, we will go ahead and
  105. // set the Query instance on the model.
  106. // -----------------------------------------------------
  107. $model->query = Query::table(static::table($class));
  108. return $model;
  109. }
  110. /**
  111. * Create a new model instance and set the relationships
  112. * that should be eagerly loaded.
  113. *
  114. * @return mixed
  115. */
  116. public static function with()
  117. {
  118. $model = static::make(get_called_class());
  119. $model->includes = func_get_args();
  120. return $model;
  121. }
  122. /**
  123. * Get a model by the primary key.
  124. *
  125. * @param int $id
  126. * @return mixed
  127. */
  128. public static function find($id)
  129. {
  130. return static::make(get_called_class())->where('id', '=', $id)->first();
  131. }
  132. /**
  133. * Get an array of models from the database.
  134. *
  135. * @return array
  136. */
  137. private function _get()
  138. {
  139. return Eloquent\Hydrator::hydrate($this);
  140. }
  141. /**
  142. * Get the first model result
  143. *
  144. * @return mixed
  145. */
  146. private function _first()
  147. {
  148. return (count($results = Eloquent\Hydrator::hydrate($this->take(1))) > 0) ? reset($results) : null;
  149. }
  150. /**
  151. * Retrieve the query for a 1:1 relationship.
  152. *
  153. * @param string $model
  154. * @param string $foreign_key
  155. * @return mixed
  156. */
  157. public function has_one($model, $foreign_key = null)
  158. {
  159. $this->relating = __FUNCTION__;
  160. return $this->has_one_or_many($model, $foreign_key);
  161. }
  162. /**
  163. * Retrieve the query for a 1:* relationship.
  164. *
  165. * @param string $model
  166. * @param string $foreign_key
  167. * @return mixed
  168. */
  169. public function has_many($model, $foreign_key = null)
  170. {
  171. $this->relating = __FUNCTION__;
  172. return $this->has_one_or_many($model, $foreign_key);
  173. }
  174. /**
  175. * Retrieve the query for a 1:1 or 1:* relationship.
  176. *
  177. * @param string $model
  178. * @param string $foreign_key
  179. * @return mixed
  180. */
  181. private function has_one_or_many($model, $foreign_key)
  182. {
  183. // -----------------------------------------------------
  184. // The default foreign key for has one and has many
  185. // relationships is the name of the model with an
  186. // appended _id.
  187. //
  188. // For example, the foreign key for a User model would
  189. // be user_id. Photo would be photo_id, etc.
  190. // -----------------------------------------------------
  191. $this->relating_key = (is_null($foreign_key)) ? Str::lower(get_class($this)).'_id' : $foreign_key;
  192. return static::make($model)->where($this->relating_key, '=', $this->id);
  193. }
  194. /**
  195. * Retrieve the query for a 1:1 belonging relationship.
  196. *
  197. * @param string $model
  198. * @param string $foreign_key
  199. * @return mixed
  200. */
  201. public function belongs_to($model, $foreign_key = null)
  202. {
  203. $this->relating = __FUNCTION__;
  204. if ( ! is_null($foreign_key))
  205. {
  206. $this->relating_key = $foreign_key;
  207. }
  208. else
  209. {
  210. // -----------------------------------------------------
  211. // The default foreign key for belonging relationships
  212. // is the name of the relationship method name with _id.
  213. //
  214. // So, if a model has a "manager" method returning a
  215. // belongs_to relationship, the key would be manager_id.
  216. // -----------------------------------------------------
  217. list(, $caller) = debug_backtrace(false);
  218. $this->relating_key = $caller['function'].'_id';
  219. }
  220. return static::make($model)->where('id', '=', $this->attributes[$this->relating_key]);
  221. }
  222. /**
  223. * Retrieve the query for a *:* relationship.
  224. *
  225. * @param string $model
  226. * @param string $table
  227. * @return mixed
  228. */
  229. public function has_and_belongs_to_many($model, $table = null)
  230. {
  231. $this->relating = __FUNCTION__;
  232. if ( ! is_null($table))
  233. {
  234. $this->relating_table = $table;
  235. }
  236. else
  237. {
  238. // -----------------------------------------------------
  239. // By default, the intermediate table name is the plural
  240. // names of the models arranged alphabetically and
  241. // concatenated with an underscore.
  242. // -----------------------------------------------------
  243. $models = array(Inflector::plural($model), Inflector::plural(get_class($this)));
  244. sort($models);
  245. $this->relating_table = Str::lower($models[0].'_'.$models[1]);
  246. }
  247. // -----------------------------------------------------
  248. // The default foreign key for many-to-many relations
  249. // is the name of the model with an appended _id.
  250. // appended _id.
  251. //
  252. // This is the same convention as has_one and has_many.
  253. // -----------------------------------------------------
  254. $this->relating_key = Str::lower(get_class($this)).'_id';
  255. return static::make($model)
  256. ->select(static::table($model).'.*')
  257. ->join($this->relating_table, static::table($model).'.id', '=', $this->relating_table.'.'.Str::lower($model).'_id')
  258. ->where($this->relating_table.'.'.$this->relating_key, '=', $this->id);
  259. }
  260. /**
  261. * Save the model to the database.
  262. *
  263. * @return bool
  264. */
  265. public function save()
  266. {
  267. // -----------------------------------------------------
  268. // If the model doesn't have any dirty attributes, there
  269. // is no need to save it to the database.
  270. // -----------------------------------------------------
  271. if ($this->exists and count($this->dirty) == 0)
  272. {
  273. return true;
  274. }
  275. $model = get_class($this);
  276. // -----------------------------------------------------
  277. // Since the model was instantiated using "new", a query
  278. // instance has not been set. We'll do it now.
  279. // -----------------------------------------------------
  280. $this->query = Query::table(static::table($model));
  281. // -----------------------------------------------------
  282. // Set the creation and update timestamps.
  283. // -----------------------------------------------------
  284. if (property_exists($model, 'timestamps') and $model::$timestamps)
  285. {
  286. $this->updated_at = date('Y-m-d H:i:s');
  287. if ( ! $this->exists)
  288. {
  289. $this->created_at = $this->updated_at;
  290. }
  291. }
  292. // -----------------------------------------------------
  293. // If the model already exists in the database, we only
  294. // need to update it. Otherwise, we'll insert it.
  295. // -----------------------------------------------------
  296. if ($this->exists)
  297. {
  298. $result = $this->query->where('id', '=', $this->attributes['id'])->update($this->dirty) == 1;
  299. }
  300. else
  301. {
  302. $this->attributes['id'] = $this->query->insert_get_id($this->attributes);
  303. $result = $this->exists = is_numeric($this->id);
  304. }
  305. $this->dirty = array();
  306. return $result;
  307. }
  308. /**
  309. * Delete a model from the database.
  310. *
  311. * @param int $id
  312. * @return int
  313. */
  314. public function delete($id = null)
  315. {
  316. // -----------------------------------------------------
  317. // If the method is being called from an existing model,
  318. // only delete that model from the database.
  319. // -----------------------------------------------------
  320. if ($this->exists)
  321. {
  322. return Query::table(static::table(get_class($this)))->delete($this->id) == 1;
  323. }
  324. return $this->query->delete($id);
  325. }
  326. /**
  327. * Magic method for retrieving model attributes.
  328. */
  329. public function __get($key)
  330. {
  331. // -----------------------------------------------------
  332. // Check the ignored attributes first. These attributes
  333. // hold all of the loaded relationships.
  334. // -----------------------------------------------------
  335. if (array_key_exists($key, $this->ignore))
  336. {
  337. return $this->ignore[$key];
  338. }
  339. // -----------------------------------------------------
  340. // Is the attribute actually a relationship method?
  341. // -----------------------------------------------------
  342. if (method_exists($this, $key))
  343. {
  344. $model = $this->$key();
  345. return ($this->relating == 'has_one' or $this->relating == 'belongs_to')
  346. ? $this->ignore[$key] = $model->first()
  347. : $this->ignore[$key] = $model->get();
  348. }
  349. return (array_key_exists($key, $this->attributes)) ? $this->attributes[$key] : null;
  350. }
  351. /**
  352. * Magic Method for setting model attributes.
  353. */
  354. public function __set($key, $value)
  355. {
  356. // -----------------------------------------------------
  357. // If the key is a relationship, add it to the ignored.
  358. // Otherwise, we can simply add it as an attribute.
  359. // -----------------------------------------------------
  360. if (method_exists($this, $key))
  361. {
  362. $this->ignore[$key] = $value;
  363. }
  364. else
  365. {
  366. $this->attributes[$key] = $value;
  367. $this->dirty[$key] = $value;
  368. }
  369. }
  370. /**
  371. * Magic Method for determining if a model attribute is set.
  372. */
  373. public function __isset($key)
  374. {
  375. return (array_key_exists($key, $this->attributes) or array_key_exists($key, $this->ignore));
  376. }
  377. /**
  378. * Magic Method for unsetting model attributes.
  379. */
  380. public function __unset($key)
  381. {
  382. unset($this->attributes[$key]);
  383. unset($this->ignore[$key]);
  384. unset($this->dirty[$key]);
  385. }
  386. /**
  387. * Magic Method for handling dynamic method calls.
  388. */
  389. public function __call($method, $parameters)
  390. {
  391. if ($method == 'get')
  392. {
  393. return $this->_get();
  394. }
  395. if ($method == 'first')
  396. {
  397. return $this->_first();
  398. }
  399. // -----------------------------------------------------
  400. // Pass aggregate methods to the query instance.
  401. // -----------------------------------------------------
  402. if (in_array($method, array('count', 'sum', 'min', 'max', 'avg')))
  403. {
  404. return call_user_func_array(array($this->query, $method), $parameters);
  405. }
  406. // -----------------------------------------------------
  407. // Pass the method to the query instance. This allows
  408. // the chaining of methods from the query builder.
  409. // -----------------------------------------------------
  410. call_user_func_array(array($this->query, $method), $parameters);
  411. return $this;
  412. }
  413. /**
  414. * Magic Method for handling dynamic static method calls.
  415. */
  416. public static function __callStatic($method, $parameters)
  417. {
  418. $model = static::make(get_called_class());
  419. if ($method == 'get')
  420. {
  421. return $model->_get();
  422. }
  423. if ($method == 'first')
  424. {
  425. return $model->_first();
  426. }
  427. // -----------------------------------------------------
  428. // Pass aggregate methods to the query instance.
  429. // -----------------------------------------------------
  430. if (in_array($method, array('count', 'sum', 'min', 'max', 'avg')))
  431. {
  432. return call_user_func_array(array($model->query, $method), $parameters);
  433. }
  434. // -----------------------------------------------------
  435. // Pass the method to the query instance. This allows
  436. // the chaining of methods from the query builder.
  437. // -----------------------------------------------------
  438. call_user_func_array(array($model->query, $method), $parameters);
  439. return $model;
  440. }
  441. }