model.php 18 KB

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