model.php 12 KB

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