model.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  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 static function find($id, $columns = array('*'))
  201. {
  202. $model = new static;
  203. return $model->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 Relationship
  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->sequence());
  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. protected function timestamp()
  384. {
  385. $this->updated_at = new \DateTime;
  386. if ( ! $this->exists) $this->created_at = $this->updated_at;
  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 ( ! isset($this->original[$key]) 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 $this->get_attribute(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 void
  488. */
  489. public function set_attribute($key, $value)
  490. {
  491. $this->attributes[$key] = $value;
  492. }
  493. /**
  494. * Remove an attribute from the model.
  495. *
  496. * @param string $key
  497. */
  498. final public function purge($key)
  499. {
  500. unset($this->original[$key]);
  501. unset($this->attributes[$key]);
  502. }
  503. /**
  504. * Get the model attributes and relationships in array form.
  505. *
  506. * @return array
  507. */
  508. public function to_array()
  509. {
  510. $attributes = array();
  511. // First we need to gather all of the regular attributes. If the attribute
  512. // exists in the array of "hidden" attributes, it will not be added to
  513. // the array so we can easily exclude things like passwords, etc.
  514. foreach (array_keys($this->attributes) as $attribute)
  515. {
  516. if ( ! in_array($attribute, static::$hidden))
  517. {
  518. $attributes[$attribute] = $this->$attribute;
  519. }
  520. }
  521. foreach ($this->relationships as $name => $models)
  522. {
  523. // If the relationship is not a "to-many" relationship, we can just
  524. // to_array the related model and add it as an attribute to the
  525. // array of existing regular attributes we gathered.
  526. if ( ! is_array($models))
  527. {
  528. $attributes[$name] = $models->to_array();
  529. }
  530. // If the relationship is a "to-many" relationship we need to spin
  531. // through each of the related models and add each one with the
  532. // to_array method, keying them both by name and ID.
  533. else
  534. {
  535. foreach ($models as $id => $model)
  536. {
  537. $attributes[$name][$id] = $model->to_array();
  538. }
  539. }
  540. }
  541. return $attributes;
  542. }
  543. /**
  544. * Fire a given event for the model.
  545. *
  546. * @param string $event
  547. * @return array
  548. */
  549. protected function fire_event($event)
  550. {
  551. $events = array("eloquent.{$event}", "eloquent.{$event}: ".get_class($this));
  552. Event::fire($events, array($this));
  553. }
  554. /**
  555. * Handle the dynamic retrieval of attributes and associations.
  556. *
  557. * @param string $key
  558. * @return mixed
  559. */
  560. public function __get($key)
  561. {
  562. // First we will check to see if the requested key is an already loaded
  563. // relationship and return it if it is. All relationships are stored
  564. // in the special relationships array so they are not persisted.
  565. if (array_key_exists($key, $this->relationships))
  566. {
  567. return $this->relationships[$key];
  568. }
  569. // Next we'll check if the requested key is in the array of attributes
  570. // for the model. These are simply regular properties that typically
  571. // correspond to a single column on the database for the model.
  572. elseif (array_key_exists($key, $this->attributes))
  573. {
  574. return $this->{"get_{$key}"}();
  575. }
  576. // If the item is not a loaded relationship, it may be a relationship
  577. // that hasn't been loaded yet. If it is, we will lazy load it and
  578. // set the value of the relationship in the relationship array.
  579. elseif (method_exists($this, $key))
  580. {
  581. return $this->relationships[$key] = $this->$key()->results();
  582. }
  583. // Finally we will just assume the requested key is just a regular
  584. // attribute and attempt to call the getter method for it, which
  585. // will fall into the __call method if one doesn't exist.
  586. else
  587. {
  588. return $this->{"get_{$key}"}();
  589. }
  590. }
  591. /**
  592. * Handle the dynamic setting of attributes.
  593. *
  594. * @param string $key
  595. * @param mixed $value
  596. * @return void
  597. */
  598. public function __set($key, $value)
  599. {
  600. $this->{"set_{$key}"}($value);
  601. }
  602. /**
  603. * Determine if an attribute exists on the model.
  604. *
  605. * @param string $key
  606. * @return bool
  607. */
  608. public function __isset($key)
  609. {
  610. foreach (array('attributes', 'relationships') as $source)
  611. {
  612. if (array_key_exists($key, $this->$source)) return true;
  613. }
  614. if (method_exists($this, $key)) return true;
  615. }
  616. /**
  617. * Remove an attribute from the model.
  618. *
  619. * @param string $key
  620. * @return void
  621. */
  622. public function __unset($key)
  623. {
  624. foreach (array('attributes', 'relationships') as $source)
  625. {
  626. unset($this->$source[$key]);
  627. }
  628. }
  629. /**
  630. * Handle dynamic method calls on the model.
  631. *
  632. * @param string $method
  633. * @param array $parameters
  634. * @return mixed
  635. */
  636. public function __call($method, $parameters)
  637. {
  638. $meta = array('key', 'table', 'connection', 'sequence', 'per_page', 'timestamps');
  639. // If the method is actually the name of a static property on the model we'll
  640. // return the value of the static property. This makes it convenient for
  641. // relationships to access these values off of the instances.
  642. if (in_array($method, $meta))
  643. {
  644. return static::$$method;
  645. }
  646. // Some methods need to be accessed both staticly and non-staticly so we'll
  647. // keep underscored methods of those methods and intercept calls to them
  648. // here so they can be called either way on the model instance.
  649. if (in_array($method, array('with')))
  650. {
  651. return call_user_func_array(array($this, '_'.$method), $parameters);
  652. }
  653. // First we want to see if the method is a getter / setter for an attribute.
  654. // If it is, we'll call the basic getter and setter method for the model
  655. // to perform the appropriate action based on the method.
  656. if (starts_with($method, 'get_'))
  657. {
  658. return $this->get_attribute(substr($method, 4));
  659. }
  660. elseif (starts_with($method, 'set_'))
  661. {
  662. $this->set_attribute(substr($method, 4), $parameters[0]);
  663. }
  664. // Finally we will assume that the method is actually the beginning of a
  665. // query, such as "where", and will create a new query instance and
  666. // call the method on the query instance, returning it after.
  667. else
  668. {
  669. return call_user_func_array(array($this->query(), $method), $parameters);
  670. }
  671. }
  672. /**
  673. * Dynamically handle static method calls on the model.
  674. *
  675. * @param string $method
  676. * @param array $parameters
  677. * @return mixed
  678. */
  679. public static function __callStatic($method, $parameters)
  680. {
  681. $model = get_called_class();
  682. return call_user_func_array(array(new $model, $method), $parameters);
  683. }
  684. }