model.php 13 KB

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