model.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801
  1. <?php namespace Laravel\Database\Eloquent;
  2. use Laravel\Str;
  3. use Laravel\Event;
  4. use Laravel\Database;
  5. use Laravel\Database\Eloquent\Relationships\Has_Many_And_Belongs_To;
  6. abstract class Model {
  7. /**
  8. * All of the model's attributes.
  9. *
  10. * @var array
  11. */
  12. public $attributes = array();
  13. /**
  14. * The model's attributes in their original state.
  15. *
  16. * @var array
  17. */
  18. public $original = array();
  19. /**
  20. * The relationships that have been loaded for the query.
  21. *
  22. * @var array
  23. */
  24. public $relationships = array();
  25. /**
  26. * Indicates if the model exists in the database.
  27. *
  28. * @var bool
  29. */
  30. public $exists = false;
  31. /**
  32. * The relationships that should be eagerly loaded.
  33. *
  34. * @var array
  35. */
  36. public $includes = array();
  37. /**
  38. * The primary key for the model on the database table.
  39. *
  40. * @var string
  41. */
  42. public static $key = 'id';
  43. /**
  44. * The attributes that are accessible for mass assignment.
  45. *
  46. * @var array
  47. */
  48. public static $accessible;
  49. /**
  50. * The attributes that should be excluded from to_array.
  51. *
  52. * @var array
  53. */
  54. public static $hidden = array();
  55. /**
  56. * Indicates if the model has update and creation timestamps.
  57. *
  58. * @var bool
  59. */
  60. public static $timestamps = true;
  61. /**
  62. * The name of the table associated with the model.
  63. *
  64. * @var string
  65. */
  66. public static $table;
  67. /**
  68. * The name of the database connection that should be used for the model.
  69. *
  70. * @var string
  71. */
  72. public static $connection;
  73. /**
  74. * The name of the sequence associated with the model.
  75. *
  76. * @var string
  77. */
  78. public static $sequence;
  79. /**
  80. * The default number of models to show per page when paginating.
  81. *
  82. * @var int
  83. */
  84. public static $per_page = 20;
  85. /**
  86. * Create a new Eloquent model instance.
  87. *
  88. * @param array $attributes
  89. * @param bool $exists
  90. * @return void
  91. */
  92. public function __construct($attributes = array(), $exists = false)
  93. {
  94. $this->exists = $exists;
  95. $this->fill($attributes);
  96. }
  97. /**
  98. * Hydrate the model with an array of attributes.
  99. *
  100. * @param array $attributes
  101. * @param bool $raw
  102. * @return Model
  103. */
  104. public function fill(array $attributes, $raw = false)
  105. {
  106. foreach ($attributes as $key => $value)
  107. {
  108. // If the "raw" flag is set, it means that we'll just load every value from
  109. // the array directly into the attributes, without any accessibility or
  110. // mutators being accounted for. What you pass in is what you get.
  111. if ($raw)
  112. {
  113. $this->set_attribute($key, $value);
  114. continue;
  115. }
  116. // If the "accessible" property is an array, the developer is limiting the
  117. // attributes that may be mass assigned, and we need to verify that the
  118. // current attribute is included in that list of allowed attributes.
  119. if (is_array(static::$accessible))
  120. {
  121. if (in_array($key, static::$accessible))
  122. {
  123. $this->$key = $value;
  124. }
  125. }
  126. // If the "accessible" property is not an array, no attributes have been
  127. // white-listed and we are free to set the value of the attribute to
  128. // the value that has been passed into the method without a check.
  129. else
  130. {
  131. $this->$key = $value;
  132. }
  133. }
  134. // If the original attribute values have not been set, we will set
  135. // them to the values passed to this method allowing us to easily
  136. // check if the model has changed since hydration.
  137. if (count($this->original) === 0)
  138. {
  139. $this->original = $this->attributes;
  140. }
  141. return $this;
  142. }
  143. /**
  144. * Fill the model with the contents of the array.
  145. *
  146. * No mutators or accessibility checks will be accounted for.
  147. *
  148. * @param array $attributes
  149. * @return Model
  150. */
  151. public function fill_raw(array $attributes)
  152. {
  153. return $this->fill($attributes, true);
  154. }
  155. /**
  156. * Set the accessible attributes for the given model.
  157. *
  158. * @param array $attributes
  159. * @return void
  160. */
  161. public static function accessible($attributes = null)
  162. {
  163. if (is_null($attributes)) return static::$accessible;
  164. static::$accessible = $attributes;
  165. }
  166. /**
  167. * Create a new model and store it in the database.
  168. *
  169. * If save is successful, the model will be returned, otherwise false.
  170. *
  171. * @param array $attributes
  172. * @return Model|false
  173. */
  174. public static function create($attributes)
  175. {
  176. $model = new static($attributes);
  177. $success = $model->save();
  178. return ($success) ? $model : false;
  179. }
  180. /**
  181. * Update a model instance in the database.
  182. *
  183. * @param mixed $id
  184. * @param array $attributes
  185. * @return int
  186. */
  187. public static function update($id, $attributes)
  188. {
  189. $model = new static(array(), true);
  190. $model->fill($attributes);
  191. if (static::$timestamps) $model->timestamp();
  192. return $model->query()->where($model->key(), '=', $id)->update($model->attributes);
  193. }
  194. /**
  195. * Get all of the models in the database.
  196. *
  197. * @return array
  198. */
  199. public static function all()
  200. {
  201. return with(new static)->query()->get();
  202. }
  203. /**
  204. * The relationships that should be eagerly loaded by the query.
  205. *
  206. * @param array $includes
  207. * @return Model
  208. */
  209. public function _with($includes)
  210. {
  211. $this->includes = (array) $includes;
  212. return $this;
  213. }
  214. /**
  215. * Get the query for a one-to-one association.
  216. *
  217. * @param string $model
  218. * @param string $foreign
  219. * @return Relationship
  220. */
  221. public function has_one($model, $foreign = null)
  222. {
  223. return $this->has_one_or_many(__FUNCTION__, $model, $foreign);
  224. }
  225. /**
  226. * Get the query for a one-to-many association.
  227. *
  228. * @param string $model
  229. * @param string $foreign
  230. * @return Relationship
  231. */
  232. public function has_many($model, $foreign = null)
  233. {
  234. return $this->has_one_or_many(__FUNCTION__, $model, $foreign);
  235. }
  236. /**
  237. * Get the query for a one-to-one / many association.
  238. *
  239. * @param string $type
  240. * @param string $model
  241. * @param string $foreign
  242. * @return Relationship
  243. */
  244. protected function has_one_or_many($type, $model, $foreign)
  245. {
  246. if ($type == 'has_one')
  247. {
  248. return new Relationships\Has_One($this, $model, $foreign);
  249. }
  250. else
  251. {
  252. return new Relationships\Has_Many($this, $model, $foreign);
  253. }
  254. }
  255. /**
  256. * Get the query for a one-to-one (inverse) relationship.
  257. *
  258. * @param string $model
  259. * @param string $foreign
  260. * @return Relationship
  261. */
  262. public function belongs_to($model, $foreign = null)
  263. {
  264. // If no foreign key is specified for the relationship, we will assume that the
  265. // name of the calling function matches the foreign key. For example, if the
  266. // calling function is "manager", we'll assume the key is "manager_id".
  267. if (is_null($foreign))
  268. {
  269. list(, $caller) = debug_backtrace(false);
  270. $foreign = "{$caller['function']}_id";
  271. }
  272. return new Relationships\Belongs_To($this, $model, $foreign);
  273. }
  274. /**
  275. * Get the query for a many-to-many relationship.
  276. *
  277. * @param string $model
  278. * @param string $table
  279. * @param string $foreign
  280. * @param string $other
  281. * @return Has_Many_And_Belongs_To
  282. */
  283. public function has_many_and_belongs_to($model, $table = null, $foreign = null, $other = null)
  284. {
  285. return new Has_Many_And_Belongs_To($this, $model, $table, $foreign, $other);
  286. }
  287. /**
  288. * Save the model and all of its relations to the database.
  289. *
  290. * @return bool
  291. */
  292. public function push()
  293. {
  294. if (!$this->save()) return false;
  295. // To sync all of the relationships to the database, we will simply spin through
  296. // the relationships, calling the "push" method on each of the models in that
  297. // given relationship, this should ensure that each model is saved.
  298. foreach ($this->relationships as $name => $models)
  299. {
  300. if ( ! is_array($models))
  301. {
  302. $models = array($models);
  303. }
  304. foreach ($models as $model)
  305. {
  306. if (!$model->push()) return false;
  307. }
  308. }
  309. return true;
  310. }
  311. /**
  312. * Save the model instance to the database.
  313. *
  314. * @return bool
  315. */
  316. public function save()
  317. {
  318. if ( ! $this->dirty()) return true;
  319. if (static::$timestamps)
  320. {
  321. $this->timestamp();
  322. }
  323. $this->fire_event('saving');
  324. // If the model exists, we only need to update it in the database, and the update
  325. // will be considered successful if there is one affected row returned from the
  326. // fluent query instance. We'll set the where condition automatically.
  327. if ($this->exists)
  328. {
  329. $query = $this->query()->where(static::$key, '=', $this->get_key());
  330. $result = $query->update($this->get_dirty()) === 1;
  331. if ($result) $this->fire_event('updated');
  332. }
  333. // If the model does not exist, we will insert the record and retrieve the last
  334. // insert ID that is associated with the model. If the ID returned is numeric
  335. // then we can consider the insert successful.
  336. else
  337. {
  338. $id = $this->query()->insert_get_id($this->attributes, $this->key());
  339. $this->set_key($id);
  340. $this->exists = $result = is_numeric($this->get_key());
  341. if ($result) $this->fire_event('created');
  342. }
  343. // After the model has been "saved", we will set the original attributes to
  344. // match the current attributes so the model will not be viewed as being
  345. // dirty and subsequent calls won't hit the database.
  346. $this->original = $this->attributes;
  347. if ($result)
  348. {
  349. $this->fire_event('saved');
  350. }
  351. return $result;
  352. }
  353. /**
  354. * Delete the model from the database.
  355. *
  356. * @return int
  357. */
  358. public function delete()
  359. {
  360. if ($this->exists)
  361. {
  362. $this->fire_event('deleting');
  363. $result = $this->query()->where(static::$key, '=', $this->get_key())->delete();
  364. $this->fire_event('deleted');
  365. return $result;
  366. }
  367. }
  368. /**
  369. * Set the update and creation timestamps on the model.
  370. *
  371. * @return void
  372. */
  373. public function timestamp()
  374. {
  375. $this->updated_at = new \DateTime;
  376. if ( ! $this->exists) $this->created_at = $this->updated_at;
  377. }
  378. /**
  379. * Updates the timestamp on the model and immediately saves it.
  380. *
  381. * @return void
  382. */
  383. public function touch()
  384. {
  385. $this->timestamp();
  386. $this->save();
  387. }
  388. /**
  389. * Get a new fluent query builder instance for the model.
  390. *
  391. * @return Query
  392. */
  393. protected function _query()
  394. {
  395. return new Query($this);
  396. }
  397. /**
  398. * Sync the original attributes with the current attributes.
  399. *
  400. * @return bool
  401. */
  402. final public function sync()
  403. {
  404. $this->original = $this->attributes;
  405. return true;
  406. }
  407. /**
  408. * Determine if a given attribute has changed from its original state.
  409. *
  410. * @param string $attribute
  411. * @return bool
  412. */
  413. public function changed($attribute)
  414. {
  415. return array_get($this->attributes, $attribute) != array_get($this->original, $attribute);
  416. }
  417. /**
  418. * Determine if the model has been changed from its original state.
  419. *
  420. * Models that haven't been persisted to storage are always considered dirty.
  421. *
  422. * @return bool
  423. */
  424. public function dirty()
  425. {
  426. return ! $this->exists or count($this->get_dirty()) > 0;
  427. }
  428. /**
  429. * Get the name of the table associated with the model.
  430. *
  431. * @return string
  432. */
  433. public function table()
  434. {
  435. return static::$table ?: strtolower(Str::plural(class_basename($this)));
  436. }
  437. /**
  438. * Get the dirty attributes for the model.
  439. *
  440. * @return array
  441. */
  442. public function get_dirty()
  443. {
  444. $dirty = array();
  445. foreach ($this->attributes as $key => $value)
  446. {
  447. if ( ! array_key_exists($key, $this->original) or $value !== $this->original[$key])
  448. {
  449. $dirty[$key] = $value;
  450. }
  451. }
  452. return $dirty;
  453. }
  454. /**
  455. * Get the value of the primary key for the model.
  456. *
  457. * @return int
  458. */
  459. public function get_key()
  460. {
  461. return array_get($this->attributes, static::$key);
  462. }
  463. /**
  464. * Set the value of the primary key for the model.
  465. *
  466. * @param int $value
  467. * @return void
  468. */
  469. public function set_key($value)
  470. {
  471. return $this->set_attribute(static::$key, $value);
  472. }
  473. /**
  474. * Get a given attribute from the model.
  475. *
  476. * @param string $key
  477. */
  478. public function get_attribute($key)
  479. {
  480. return array_get($this->attributes, $key);
  481. }
  482. /**
  483. * Set an attribute's value on the model.
  484. *
  485. * @param string $key
  486. * @param mixed $value
  487. * @return Model
  488. */
  489. public function set_attribute($key, $value)
  490. {
  491. $this->attributes[$key] = $value;
  492. return $this;
  493. }
  494. /**
  495. * Remove an attribute from the model.
  496. *
  497. * @param string $key
  498. */
  499. final public function purge($key)
  500. {
  501. unset($this->original[$key]);
  502. unset($this->attributes[$key]);
  503. }
  504. /**
  505. * Get the model attributes and relationships in array form.
  506. *
  507. * @return array
  508. */
  509. public function to_array()
  510. {
  511. $attributes = array();
  512. // First we need to gather all of the regular attributes. If the attribute
  513. // exists in the array of "hidden" attributes, it will not be added to
  514. // the array so we can easily exclude things like passwords, etc.
  515. foreach (array_keys($this->attributes) as $attribute)
  516. {
  517. if ( ! in_array($attribute, static::$hidden))
  518. {
  519. $attributes[$attribute] = $this->$attribute;
  520. }
  521. }
  522. foreach ($this->relationships as $name => $models)
  523. {
  524. // Relationships can be marked as "hidden", too.
  525. if (in_array($name, static::$hidden)) continue;
  526. // If the relationship is not a "to-many" relationship, we can just
  527. // to_array the related model and add it as an attribute to the
  528. // array of existing regular attributes we gathered.
  529. if ($models instanceof Model)
  530. {
  531. $attributes[$name] = $models->to_array();
  532. }
  533. // If the relationship is a "to-many" relationship we need to spin
  534. // through each of the related models and add each one with the
  535. // to_array method, keying them both by name and ID.
  536. elseif (is_array($models))
  537. {
  538. $attributes[$name] = array();
  539. foreach ($models as $id => $model)
  540. {
  541. $attributes[$name][$id] = $model->to_array();
  542. }
  543. }
  544. elseif (is_null($models))
  545. {
  546. $attributes[$name] = $models;
  547. }
  548. }
  549. return $attributes;
  550. }
  551. /**
  552. * Fire a given event for the model.
  553. *
  554. * @param string $event
  555. * @return array
  556. */
  557. protected function fire_event($event)
  558. {
  559. $events = array("eloquent.{$event}", "eloquent.{$event}: ".get_class($this));
  560. Event::fire($events, array($this));
  561. }
  562. /**
  563. * Handle the dynamic retrieval of attributes and associations.
  564. *
  565. * @param string $key
  566. * @return mixed
  567. */
  568. public function __get($key)
  569. {
  570. // First we will check to see if the requested key is an already loaded
  571. // relationship and return it if it is. All relationships are stored
  572. // in the special relationships array so they are not persisted.
  573. if (array_key_exists($key, $this->relationships))
  574. {
  575. return $this->relationships[$key];
  576. }
  577. // Next we'll check if the requested key is in the array of attributes
  578. // for the model. These are simply regular properties that typically
  579. // correspond to a single column on the database for the model.
  580. elseif (array_key_exists($key, $this->attributes))
  581. {
  582. return $this->{"get_{$key}"}();
  583. }
  584. // If the item is not a loaded relationship, it may be a relationship
  585. // that hasn't been loaded yet. If it is, we will lazy load it and
  586. // set the value of the relationship in the relationship array.
  587. elseif (method_exists($this, $key))
  588. {
  589. return $this->relationships[$key] = $this->$key()->results();
  590. }
  591. // Finally we will just assume the requested key is just a regular
  592. // attribute and attempt to call the getter method for it, which
  593. // will fall into the __call method if one doesn't exist.
  594. else
  595. {
  596. return $this->{"get_{$key}"}();
  597. }
  598. }
  599. /**
  600. * Handle the dynamic setting of attributes.
  601. *
  602. * @param string $key
  603. * @param mixed $value
  604. * @return void
  605. */
  606. public function __set($key, $value)
  607. {
  608. $this->{"set_{$key}"}($value);
  609. }
  610. /**
  611. * Determine if an attribute exists on the model.
  612. *
  613. * @param string $key
  614. * @return bool
  615. */
  616. public function __isset($key)
  617. {
  618. foreach (array('attributes', 'relationships') as $source)
  619. {
  620. if (array_key_exists($key, $this->{$source})) return ! empty($this->{$source}[$key]);
  621. }
  622. return false;
  623. }
  624. /**
  625. * Remove an attribute from the model.
  626. *
  627. * @param string $key
  628. * @return void
  629. */
  630. public function __unset($key)
  631. {
  632. foreach (array('attributes', 'relationships') as $source)
  633. {
  634. unset($this->{$source}[$key]);
  635. }
  636. }
  637. /**
  638. * Handle dynamic method calls on the model.
  639. *
  640. * @param string $method
  641. * @param array $parameters
  642. * @return mixed
  643. */
  644. public function __call($method, $parameters)
  645. {
  646. $meta = array('key', 'table', 'connection', 'sequence', 'per_page', 'timestamps');
  647. // If the method is actually the name of a static property on the model we'll
  648. // return the value of the static property. This makes it convenient for
  649. // relationships to access these values off of the instances.
  650. if (in_array($method, $meta))
  651. {
  652. return static::$$method;
  653. }
  654. $underscored = array('with', 'query');
  655. // Some methods need to be accessed both staticly and non-staticly so we'll
  656. // keep underscored methods of those methods and intercept calls to them
  657. // here so they can be called either way on the model instance.
  658. if (in_array($method, $underscored))
  659. {
  660. return call_user_func_array(array($this, '_'.$method), $parameters);
  661. }
  662. // First we want to see if the method is a getter / setter for an attribute.
  663. // If it is, we'll call the basic getter and setter method for the model
  664. // to perform the appropriate action based on the method.
  665. if (starts_with($method, 'get_'))
  666. {
  667. return $this->get_attribute(substr($method, 4));
  668. }
  669. elseif (starts_with($method, 'set_'))
  670. {
  671. return $this->set_attribute(substr($method, 4), $parameters[0]);
  672. }
  673. // Finally we will assume that the method is actually the beginning of a
  674. // query, such as "where", and will create a new query instance and
  675. // call the method on the query instance, returning it after.
  676. else
  677. {
  678. return call_user_func_array(array($this->query(), $method), $parameters);
  679. }
  680. }
  681. /**
  682. * Dynamically handle static method calls on the model.
  683. *
  684. * @param string $method
  685. * @param array $parameters
  686. * @return mixed
  687. */
  688. public static function __callStatic($method, $parameters)
  689. {
  690. $model = get_called_class();
  691. return call_user_func_array(array(new $model, $method), $parameters);
  692. }
  693. }