model.php 13 KB

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