model.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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. if (static::$timestamps) $attributes['updated_at'] = new \DateTime;
  191. return $model->query()->where($model->key(), '=', $id)->update($attributes);
  192. }
  193. /**
  194. * Find a model by its primary key.
  195. *
  196. * @param string $id
  197. * @param array $columns
  198. * @return Model
  199. */
  200. public function _find($id, $columns = array('*'))
  201. {
  202. return $this->query()->where(static::$key, '=', $id)->first($columns);
  203. }
  204. /**
  205. * Get all of the models in the database.
  206. *
  207. * @return array
  208. */
  209. public static function all()
  210. {
  211. return with(new static)->query()->get();
  212. }
  213. /**
  214. * The relationships that should be eagerly loaded by the query.
  215. *
  216. * @param array $includes
  217. * @return Model
  218. */
  219. public function _with($includes)
  220. {
  221. $this->includes = (array) $includes;
  222. return $this;
  223. }
  224. /**
  225. * Get the query for a one-to-one association.
  226. *
  227. * @param string $model
  228. * @param string $foreign
  229. * @return Relationship
  230. */
  231. public function has_one($model, $foreign = null)
  232. {
  233. return $this->has_one_or_many(__FUNCTION__, $model, $foreign);
  234. }
  235. /**
  236. * Get the query for a one-to-many association.
  237. *
  238. * @param string $model
  239. * @param string $foreign
  240. * @return Relationship
  241. */
  242. public function has_many($model, $foreign = null)
  243. {
  244. return $this->has_one_or_many(__FUNCTION__, $model, $foreign);
  245. }
  246. /**
  247. * Get the query for a one-to-one / many association.
  248. *
  249. * @param string $type
  250. * @param string $model
  251. * @param string $foreign
  252. * @return Relationship
  253. */
  254. protected function has_one_or_many($type, $model, $foreign)
  255. {
  256. if ($type == 'has_one')
  257. {
  258. return new Relationships\Has_One($this, $model, $foreign);
  259. }
  260. else
  261. {
  262. return new Relationships\Has_Many($this, $model, $foreign);
  263. }
  264. }
  265. /**
  266. * Get the query for a one-to-one (inverse) relationship.
  267. *
  268. * @param string $model
  269. * @param string $foreign
  270. * @return Relationship
  271. */
  272. public function belongs_to($model, $foreign = null)
  273. {
  274. // If no foreign key is specified for the relationship, we will assume that the
  275. // name of the calling function matches the foreign key. For example, if the
  276. // calling function is "manager", we'll assume the key is "manager_id".
  277. if (is_null($foreign))
  278. {
  279. list(, $caller) = debug_backtrace(false);
  280. $foreign = "{$caller['function']}_id";
  281. }
  282. return new Relationships\Belongs_To($this, $model, $foreign);
  283. }
  284. /**
  285. * Get the query for a many-to-many relationship.
  286. *
  287. * @param string $model
  288. * @param string $table
  289. * @param string $foreign
  290. * @param string $other
  291. * @return Relationship
  292. */
  293. public function has_many_and_belongs_to($model, $table = null, $foreign = null, $other = null)
  294. {
  295. return new Has_Many_And_Belongs_To($this, $model, $table, $foreign, $other);
  296. }
  297. /**
  298. * Save the model and all of its relations to the database.
  299. *
  300. * @return bool
  301. */
  302. public function push()
  303. {
  304. $this->save();
  305. // To sync all of the relationships to the database, we will simply spin through
  306. // the relationships, calling the "push" method on each of the models in that
  307. // given relationship, this should ensure that each model is saved.
  308. foreach ($this->relationships as $name => $models)
  309. {
  310. if ( ! is_array($models))
  311. {
  312. $models = array($models);
  313. }
  314. foreach ($models as $model)
  315. {
  316. $model->push();
  317. }
  318. }
  319. }
  320. /**
  321. * Save the model instance to the database.
  322. *
  323. * @return bool
  324. */
  325. public function save()
  326. {
  327. if ( ! $this->dirty()) return true;
  328. if (static::$timestamps)
  329. {
  330. $this->timestamp();
  331. }
  332. $this->fire_event('saving');
  333. // If the model exists, we only need to update it in the database, and the update
  334. // will be considered successful if there is one affected row returned from the
  335. // fluent query instance. We'll set the where condition automatically.
  336. if ($this->exists)
  337. {
  338. $query = $this->query()->where(static::$key, '=', $this->get_key());
  339. $result = $query->update($this->get_dirty()) === 1;
  340. if ($result) $this->fire_event('updated');
  341. }
  342. // If the model does not exist, we will insert the record and retrieve the last
  343. // insert ID that is associated with the model. If the ID returned is numeric
  344. // then we can consider the insert successful.
  345. else
  346. {
  347. $id = $this->query()->insert_get_id($this->attributes, $this->key());
  348. $this->set_key($id);
  349. $this->exists = $result = is_numeric($this->get_key());
  350. if ($result) $this->fire_event('created');
  351. }
  352. // After the model has been "saved", we will set the original attributes to
  353. // match the current attributes so the model will not be viewed as being
  354. // dirty and subsequent calls won't hit the database.
  355. $this->original = $this->attributes;
  356. if ($result)
  357. {
  358. $this->fire_event('saved');
  359. }
  360. return $result;
  361. }
  362. /**
  363. * Delete the model from the database.
  364. *
  365. * @return int
  366. */
  367. public function delete()
  368. {
  369. if ($this->exists)
  370. {
  371. $this->fire_event('deleting');
  372. $result = $this->query()->where(static::$key, '=', $this->get_key())->delete();
  373. $this->fire_event('deleted');
  374. return $result;
  375. }
  376. }
  377. /**
  378. * Set the update and creation timestamps on the model.
  379. *
  380. * @return void
  381. */
  382. protected function timestamp()
  383. {
  384. $this->updated_at = new \DateTime;
  385. if ( ! $this->exists) $this->created_at = $this->updated_at;
  386. }
  387. /**
  388. * Get a new fluent query builder instance for the model.
  389. *
  390. * @return Query
  391. */
  392. protected function query()
  393. {
  394. return new Query($this);
  395. }
  396. /**
  397. * Sync the original attributes with the current attributes.
  398. *
  399. * @return bool
  400. */
  401. final public function sync()
  402. {
  403. $this->original = $this->attributes;
  404. return true;
  405. }
  406. /**
  407. * Determine if a given attribute has changed from its original state.
  408. *
  409. * @param string $attribute
  410. * @return bool
  411. */
  412. public function changed($attribute)
  413. {
  414. return array_get($this->attributes, $attribute) !== array_get($this->original, $attribute);
  415. }
  416. /**
  417. * Determine if the model has been changed from its original state.
  418. *
  419. * Models that haven't been persisted to storage are always considered dirty.
  420. *
  421. * @return bool
  422. */
  423. public function dirty()
  424. {
  425. return ! $this->exists or count($this->get_dirty()) > 0;
  426. }
  427. /**
  428. * Get the name of the table associated with the model.
  429. *
  430. * @return string
  431. */
  432. public function table()
  433. {
  434. return static::$table ?: strtolower(Str::plural(class_basename($this)));
  435. }
  436. /**
  437. * Get the dirty attributes for the model.
  438. *
  439. * @return array
  440. */
  441. public function get_dirty()
  442. {
  443. $dirty = array();
  444. foreach ($this->attributes as $key => $value)
  445. {
  446. if ( ! isset($this->original[$key]) or $value !== $this->original[$key])
  447. {
  448. $dirty[$key] = $value;
  449. }
  450. }
  451. return $dirty;
  452. }
  453. /**
  454. * Get the value of the primary key for the model.
  455. *
  456. * @return int
  457. */
  458. public function get_key()
  459. {
  460. return $this->get_attribute(static::$key);
  461. }
  462. /**
  463. * Set the value of the primary key for the model.
  464. *
  465. * @param int $value
  466. * @return void
  467. */
  468. public function set_key($value)
  469. {
  470. return $this->set_attribute(static::$key, $value);
  471. }
  472. /**
  473. * Get a given attribute from the model.
  474. *
  475. * @param string $key
  476. */
  477. public function get_attribute($key)
  478. {
  479. return array_get($this->attributes, $key);
  480. }
  481. /**
  482. * Set an attribute's value on the model.
  483. *
  484. * @param string $key
  485. * @param mixed $value
  486. * @return void
  487. */
  488. public function set_attribute($key, $value)
  489. {
  490. $this->attributes[$key] = $value;
  491. }
  492. /**
  493. * Remove an attribute from the model.
  494. *
  495. * @param string $key
  496. */
  497. final public function purge($key)
  498. {
  499. unset($this->original[$key]);
  500. unset($this->attributes[$key]);
  501. }
  502. /**
  503. * Get the model attributes and relationships in array form.
  504. *
  505. * @return array
  506. */
  507. public function to_array()
  508. {
  509. $attributes = array();
  510. // First we need to gather all of the regular attributes. If the attribute
  511. // exists in the array of "hidden" attributes, it will not be added to
  512. // the array so we can easily exclude things like passwords, etc.
  513. foreach (array_keys($this->attributes) as $attribute)
  514. {
  515. if ( ! in_array($attribute, static::$hidden))
  516. {
  517. $attributes[$attribute] = $this->$attribute;
  518. }
  519. }
  520. foreach ($this->relationships as $name => $models)
  521. {
  522. // If the relationship is not a "to-many" relationship, we can just
  523. // to_array the related model and add it as an attribute to the
  524. // array of existing regular attributes we gathered.
  525. if ($models instanceof Model)
  526. {
  527. $attributes[$name] = $models->to_array();
  528. }
  529. // If the relationship is a "to-many" relationship we need to spin
  530. // through each of the related models and add each one with the
  531. // to_array method, keying them both by name and ID.
  532. elseif (is_array($models))
  533. {
  534. foreach ($models as $id => $model)
  535. {
  536. $attributes[$name][$id] = $model->to_array();
  537. }
  538. }
  539. elseif (is_null($models))
  540. {
  541. $attributes[$name] = $models;
  542. }
  543. }
  544. return $attributes;
  545. }
  546. /**
  547. * Fire a given event for the model.
  548. *
  549. * @param string $event
  550. * @return array
  551. */
  552. protected function fire_event($event)
  553. {
  554. $events = array("eloquent.{$event}", "eloquent.{$event}: ".get_class($this));
  555. Event::fire($events, array($this));
  556. }
  557. /**
  558. * Handle the dynamic retrieval of attributes and associations.
  559. *
  560. * @param string $key
  561. * @return mixed
  562. */
  563. public function __get($key)
  564. {
  565. // First we will check to see if the requested key is an already loaded
  566. // relationship and return it if it is. All relationships are stored
  567. // in the special relationships array so they are not persisted.
  568. if (array_key_exists($key, $this->relationships))
  569. {
  570. return $this->relationships[$key];
  571. }
  572. // Next we'll check if the requested key is in the array of attributes
  573. // for the model. These are simply regular properties that typically
  574. // correspond to a single column on the database for the model.
  575. elseif (array_key_exists($key, $this->attributes))
  576. {
  577. return $this->{"get_{$key}"}();
  578. }
  579. // If the item is not a loaded relationship, it may be a relationship
  580. // that hasn't been loaded yet. If it is, we will lazy load it and
  581. // set the value of the relationship in the relationship array.
  582. elseif (method_exists($this, $key))
  583. {
  584. return $this->relationships[$key] = $this->$key()->results();
  585. }
  586. // Finally we will just assume the requested key is just a regular
  587. // attribute and attempt to call the getter method for it, which
  588. // will fall into the __call method if one doesn't exist.
  589. else
  590. {
  591. return $this->{"get_{$key}"}();
  592. }
  593. }
  594. /**
  595. * Handle the dynamic setting of attributes.
  596. *
  597. * @param string $key
  598. * @param mixed $value
  599. * @return void
  600. */
  601. public function __set($key, $value)
  602. {
  603. $this->{"set_{$key}"}($value);
  604. }
  605. /**
  606. * Determine if an attribute exists on the model.
  607. *
  608. * @param string $key
  609. * @return bool
  610. */
  611. public function __isset($key)
  612. {
  613. foreach (array('attributes', 'relationships') as $source)
  614. {
  615. if (array_key_exists($key, $this->$source)) return true;
  616. }
  617. if (method_exists($this, $key)) return true;
  618. }
  619. /**
  620. * Remove an attribute from the model.
  621. *
  622. * @param string $key
  623. * @return void
  624. */
  625. public function __unset($key)
  626. {
  627. foreach (array('attributes', 'relationships') as $source)
  628. {
  629. unset($this->$source[$key]);
  630. }
  631. }
  632. /**
  633. * Handle dynamic method calls on the model.
  634. *
  635. * @param string $method
  636. * @param array $parameters
  637. * @return mixed
  638. */
  639. public function __call($method, $parameters)
  640. {
  641. $meta = array('key', 'table', 'connection', 'sequence', 'per_page', 'timestamps');
  642. // If the method is actually the name of a static property on the model, we'll
  643. // return the value of the static property. This makes it convenient for
  644. // relationships to access these values off of the instances.
  645. if (in_array($method, $meta))
  646. {
  647. return static::$$method;
  648. }
  649. $underscored = array('with', 'find');
  650. // Some methods need to be accessed both statically and non-statically so we'll
  651. // keep underscored methods of those methods and intercept calls to them
  652. // here so they can be called either way on the model instance.
  653. if (in_array($method, $underscored))
  654. {
  655. return call_user_func_array(array($this, '_'.$method), $parameters);
  656. }
  657. // First we want to see if the method is a getter / setter for an attribute.
  658. // If it is, we'll call the basic getter and setter method for the model
  659. // to perform the appropriate action based on the method.
  660. if (starts_with($method, 'get_'))
  661. {
  662. return $this->get_attribute(substr($method, 4));
  663. }
  664. elseif (starts_with($method, 'set_'))
  665. {
  666. $this->set_attribute(substr($method, 4), $parameters[0]);
  667. }
  668. // Finally we will assume that the method is actually the beginning of a
  669. // query, such as "where", and will create a new query instance and
  670. // call the method on the query instance, returning it after.
  671. else
  672. {
  673. return call_user_func_array(array($this->query(), $method), $parameters);
  674. }
  675. }
  676. /**
  677. * Dynamically handle static method calls on the model.
  678. *
  679. * @param string $method
  680. * @param array $parameters
  681. * @return mixed
  682. */
  683. public static function __callStatic($method, $parameters)
  684. {
  685. $model = get_called_class();
  686. return call_user_func_array(array(new $model, $method), $parameters);
  687. }
  688. }