PageRenderTime 58ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/system/libraries/ORM.php

https://github.com/Toushi/flow
PHP | 1095 lines | 587 code | 136 blank | 372 comment | 61 complexity | b220efdfd58731a12cdb76925f9b8093 MD5 | raw file
  1. <?php defined('SYSPATH') or die('No direct script access.');
  2. /**
  3. * Object Relational Mapping (ORM) is a method of abstracting database
  4. * access to standard PHP calls. All table rows are represented as a model.
  5. *
  6. * @see http://en.wikipedia.org/wiki/Active_record
  7. * @see http://en.wikipedia.org/wiki/Object-relational_mapping
  8. *
  9. * $Id: ORM.php 3304 2008-08-08 18:45:30Z Shadowhand $
  10. *
  11. * @package Core
  12. * @author Kohana Team
  13. * @copyright (c) 2007-2008 Kohana Team
  14. * @license http://kohanaphp.com/license.html
  15. */
  16. class ORM_Core {
  17. // Current relationships
  18. protected $has_one = array();
  19. protected $belongs_to = array();
  20. protected $has_many = array();
  21. protected $has_and_belongs_to_many = array();
  22. // Current object
  23. protected $object = array();
  24. protected $changed = array();
  25. protected $loaded = FALSE;
  26. protected $saved = FALSE;
  27. protected $sorting = array('id' => 'asc');
  28. // Related objects
  29. protected $related = array();
  30. // Model table information
  31. protected $object_name;
  32. protected $table_name;
  33. protected $table_columns;
  34. protected $ignored_columns;
  35. // Table primary key and value
  36. protected $primary_key = 'id';
  37. protected $primary_val = 'name';
  38. // Model configuration
  39. protected $table_names_plural = TRUE;
  40. protected $reload_on_wakeup = TRUE;
  41. // Database configuration
  42. protected $db = 'default';
  43. protected $db_applied = array();
  44. /**
  45. * Creates and returns a new model.
  46. *
  47. * @chainable
  48. * @param string model name
  49. * @param mixed parameter for find()
  50. * @return ORM
  51. */
  52. public static function factory($model, $id = NULL)
  53. {
  54. // Set class name
  55. $model = ucfirst($model).'_Model';
  56. return new $model($id);
  57. }
  58. /**
  59. * Prepares the model database connection and loads the object.
  60. *
  61. * @param mixed parameter for find or object to load
  62. * @return void
  63. */
  64. public function __construct($id = NULL)
  65. {
  66. // Set the object name
  67. $this->object_name = strtolower(substr(get_class($this), 0, -6));
  68. // Initialize database
  69. $this->__initialize();
  70. if ($id === NULL OR $id === '')
  71. {
  72. // Clear the object
  73. $this->clear();
  74. }
  75. elseif (is_object($id))
  76. {
  77. // Object is loaded and saved
  78. $this->loaded = $this->saved = TRUE;
  79. // Load an object
  80. $this->load_values((array) $id);
  81. }
  82. else
  83. {
  84. // Find an object
  85. $this->find($id);
  86. }
  87. }
  88. /**
  89. * Prepares the model database connection, determines the table name,
  90. * and loads column information.
  91. *
  92. * @return void
  93. */
  94. public function __initialize()
  95. {
  96. if ( ! is_object($this->db))
  97. {
  98. // Get database instance
  99. $this->db = Database::instance($this->db);
  100. }
  101. if (empty($this->table_name))
  102. {
  103. // Table name is the same as the object name
  104. $this->table_name = $this->object_name;
  105. if ($this->table_names_plural === TRUE)
  106. {
  107. // Make the table name plural
  108. $this->table_name = inflector::plural($this->table_name);
  109. }
  110. }
  111. if (is_array($this->ignored_columns))
  112. {
  113. // Make the ignored columns mirrored = mirrored
  114. $this->ignored_columns = array_combine($this->ignored_columns, $this->ignored_columns);
  115. }
  116. // Load column information
  117. $this->reload_columns();
  118. }
  119. /**
  120. * Allows serialization of only the object data and state, to prevent
  121. * "stale" objects being unserialized, which also requires less memory.
  122. *
  123. * @return array
  124. */
  125. public function __sleep()
  126. {
  127. // Store only information about the object
  128. return array('object_name', 'object', 'changed', 'loaded', 'saved', 'sorting');
  129. }
  130. /**
  131. * Prepares the database connection and reloads the object.
  132. *
  133. * @return void
  134. */
  135. public function __wakeup()
  136. {
  137. // Initialize database
  138. $this->__initialize();
  139. if ($this->reload_on_wakeup === TRUE)
  140. {
  141. // Reload the object
  142. $this->reload();
  143. }
  144. }
  145. /**
  146. * Handles pass-through to database methods. Calls to query methods
  147. * (query, get, insert, update) are not allowed. Query builder methods
  148. * are chainable.
  149. *
  150. * @param string method name
  151. * @param array method arguments
  152. * @return mixed
  153. */
  154. public function __call($method, array $args)
  155. {
  156. if (method_exists($this->db, $method))
  157. {
  158. if (in_array($method, array('query', 'get', 'insert', 'update', 'delete')))
  159. throw new Kohana_Exception('orm.query_methods_not_allowed');
  160. // Method has been applied to the database
  161. $this->db_applied[$method] = $method;
  162. // Number of arguments passed
  163. $num_args = count($args);
  164. if ($method === 'select' AND $num_args > 3)
  165. {
  166. // Call select() manually to avoid call_user_func_array
  167. $this->db->select($args);
  168. }
  169. else
  170. {
  171. // We use switch here to manually call the database methods. This is
  172. // done for speed: call_user_func_array can take over 300% longer to
  173. // make calls. Mose database methods are 4 arguments or less, so this
  174. // avoids almost any calls to call_user_func_array.
  175. switch ($num_args)
  176. {
  177. case 0:
  178. // Support for things like reset_select, reset_write, list_tables
  179. return $this->db->$method();
  180. break;
  181. case 1:
  182. $this->db->$method($args[0]);
  183. break;
  184. case 2:
  185. $this->db->$method($args[0], $args[1]);
  186. break;
  187. case 3:
  188. $this->db->$method($args[0], $args[1], $args[2]);
  189. break;
  190. case 4:
  191. $this->db->$method($args[0], $args[1], $args[2], $args[3]);
  192. break;
  193. default:
  194. // Here comes the snail...
  195. call_user_func_array(array($this->db, $method), $args);
  196. break;
  197. }
  198. }
  199. return $this;
  200. }
  201. else
  202. {
  203. throw new Kohana_Exception('core.invalid_method', $method, get_class($this));
  204. }
  205. }
  206. /**
  207. * Handles retrieval of all model values, relationships, and metadata.
  208. *
  209. * @param string column name
  210. * @return mixed
  211. */
  212. public function __get($column)
  213. {
  214. if (isset($this->ignored_columns[$column]))
  215. {
  216. return NULL;
  217. }
  218. elseif (isset($this->object[$column]) OR array_key_exists($column, $this->object))
  219. {
  220. return $this->object[$column];
  221. }
  222. elseif (isset($this->related[$column]))
  223. {
  224. return $this->related[$column];
  225. }
  226. elseif ($column === 'primary_key_value')
  227. {
  228. return $this->object[$this->primary_key];
  229. }
  230. elseif (($owner = isset($this->has_one[$column])) OR isset($this->belongs_to[$column]))
  231. {
  232. // Determine the model name
  233. $model = ($owner === TRUE) ? $this->has_one[$column] : $this->belongs_to[$column];
  234. // Load model
  235. $model = ORM::factory($model);
  236. if (isset($this->object[$column.'_'.$model->primary_key]))
  237. {
  238. // Use the FK that exists in this model as the PK
  239. $where = array($model->primary_key => $this->object[$column.'_'.$model->primary_key]);
  240. }
  241. else
  242. {
  243. // Use this model PK as the FK
  244. $where = array($this->foreign_key() => $this->object[$this->primary_key]);
  245. }
  246. // one<>alias:one relationship
  247. return $this->related[$column] = $model->find($where);
  248. }
  249. elseif (in_array($column, $this->has_one) OR in_array($column, $this->belongs_to))
  250. {
  251. $model = ORM::factory($column);
  252. if (isset($this->object[$column.'_'.$model->primary_key]))
  253. {
  254. // Use the FK that exists in this model as the PK
  255. $where = array($model->primary_key => $this->object[$column.'_'.$model->primary_key]);
  256. }
  257. else
  258. {
  259. // Use this model PK as the FK
  260. $where = array($this->foreign_key() => $this->object[$this->primary_key]);
  261. }
  262. // one<>one relationship
  263. return $this->related[$column] = ORM::factory($column, $where);
  264. }
  265. elseif (isset($this->has_many[$column]))
  266. {
  267. // Load the "middle" model
  268. $through = ORM::factory(inflector::singular($this->has_many[$column]));
  269. // Load the "end" model
  270. $model = ORM::factory(inflector::singular($column));
  271. // Load JOIN info
  272. $join_table = $through->table_name;
  273. $join_col1 = $model->foreign_key(NULL, $join_table);
  274. $join_col2 = $model->foreign_key(TRUE);
  275. // one<>alias:many relationship
  276. return $this->related[$column] = $model
  277. ->join($join_table, $join_col1, $join_col2)
  278. ->where($this->foreign_key(NULL, $join_table), $this->object[$this->primary_key])
  279. ->find_all();
  280. }
  281. elseif (in_array($column, $this->has_many))
  282. {
  283. // one<>many relationship
  284. return $this->related[$column] = ORM::factory(inflector::singular($column))
  285. ->where($this->foreign_key($column), $this->object[$this->primary_key])
  286. ->find_all();
  287. }
  288. elseif (in_array($column, $this->has_and_belongs_to_many))
  289. {
  290. // Load the remote model, always singular
  291. $model = ORM::factory(inflector::singular($column));
  292. // Load JOIN info
  293. $join_table = $model->join_table($this->table_name);
  294. $join_col1 = $model->foreign_key(NULL, $join_table);
  295. $join_col2 = $model->foreign_key(TRUE);
  296. // many<>many relationship
  297. return $this->related[$column] = $model
  298. ->join($join_table, $join_col1, $join_col2)
  299. ->where($this->foreign_key(NULL, $join_table), $this->object[$this->primary_key])
  300. ->find_all();
  301. }
  302. elseif (in_array($column, array
  303. (
  304. 'object_name', // Object
  305. 'primary_key', 'primary_val', 'table_name', 'table_columns', // Table
  306. 'loaded', 'saved', // Status
  307. 'has_one', 'belongs_to', 'has_many', 'has_and_belongs_to_many', // Relationships
  308. )))
  309. {
  310. // Model meta information
  311. return $this->$column;
  312. }
  313. else
  314. {
  315. throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
  316. }
  317. }
  318. /**
  319. * Handles setting of all model values, and tracks changes between values.
  320. *
  321. * @param string column name
  322. * @param mixed column value
  323. * @return void
  324. */
  325. public function __set($column, $value)
  326. {
  327. if (isset($this->ignored_columns[$column]))
  328. {
  329. return NULL;
  330. }
  331. elseif (isset($this->object[$column]) OR array_key_exists($column, $this->object))
  332. {
  333. if (isset($this->table_columns[$column]))
  334. {
  335. // Data has changed
  336. $this->changed[$column] = $column;
  337. // Object is no longer saved
  338. $this->saved = FALSE;
  339. }
  340. $this->object[$column] = $this->load_type($column, $value);
  341. }
  342. else
  343. {
  344. throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
  345. }
  346. }
  347. /**
  348. * Checks if object data is set.
  349. *
  350. * @param string column name
  351. * @return boolean
  352. */
  353. public function __isset($column)
  354. {
  355. return (isset($this->object[$column]) OR isset($this->related[$column]));
  356. }
  357. /**
  358. * Unsets object data.
  359. *
  360. * @param string column name
  361. * @return void
  362. */
  363. public function __unset($column)
  364. {
  365. unset($this->object[$column], $this->changed[$column], $this->related[$column]);
  366. }
  367. /**
  368. * Displays the primary key of a model when it is converted to a string.
  369. *
  370. * @return string
  371. */
  372. public function __toString()
  373. {
  374. return (string) $this->object[$this->primary_key];
  375. }
  376. /**
  377. * Returns the values of this object as an array.
  378. *
  379. * @return array
  380. */
  381. public function as_array()
  382. {
  383. return $this->object;
  384. }
  385. /**
  386. * Finds and loads a single database row into the object.
  387. *
  388. * @chainable
  389. * @param mixed primary key or an array of clauses
  390. * @return ORM
  391. */
  392. public function find($id = NULL)
  393. {
  394. if ($id !== NULL)
  395. {
  396. if (is_array($id))
  397. {
  398. // Search for all clauses
  399. $this->db->where($id);
  400. }
  401. else
  402. {
  403. // Search for a specific column
  404. $this->db->where($this->unique_key($id), $id);
  405. }
  406. }
  407. return $this->load_result();
  408. }
  409. /**
  410. * Finds multiple database rows and returns an iterator of the rows found.
  411. *
  412. * @chainable
  413. * @param integer SQL limit
  414. * @param integer SQL offset
  415. * @return ORM_Iterator
  416. */
  417. public function find_all($limit = NULL, $offset = 0)
  418. {
  419. if ($limit !== NULL)
  420. {
  421. // Set limit
  422. $this->db->limit($limit);
  423. }
  424. if ($offset !== NULL)
  425. {
  426. // Set offset
  427. $this->db->offset($offset);
  428. }
  429. if ( ! isset($this->db_applied['orderby']))
  430. {
  431. // Apply sorting
  432. $this->db->orderby($this->sorting);
  433. }
  434. return $this->load_result(TRUE);
  435. }
  436. /**
  437. * Creates a key/value array from all of the objects available. Uses find_all
  438. * to find the objects.
  439. *
  440. * @param string key column
  441. * @param string value column
  442. * @return array
  443. */
  444. public function select_list($key, $val)
  445. {
  446. // Return a select list from the results
  447. return $this->select($key, $val)->find_all()->select_list($key, $val);
  448. }
  449. /**
  450. * Validates the current object. This method should generally be called
  451. * via the model, after the $_POST Validation object has been created.
  452. *
  453. * @param object Validation array
  454. * @return boolean
  455. */
  456. public function validate(Validation $array, $save = FALSE)
  457. {
  458. if ( ! $array->submitted())
  459. {
  460. $safe_array = $array->safe_array();
  461. foreach ($safe_array as $key => $val)
  462. {
  463. // Pre-fill data
  464. $array[$key] = $this->$key;
  465. }
  466. }
  467. // Validate the array
  468. if ($status = $array->validate())
  469. {
  470. $safe_array = $array->safe_array();
  471. foreach ($safe_array as $key => $val)
  472. {
  473. // Set new data
  474. $this->$key = $val;
  475. }
  476. if ($save === TRUE OR is_string($save))
  477. {
  478. // Save this object
  479. $this->save();
  480. if (is_string($save))
  481. {
  482. // Redirect to the saved page
  483. url::redirect($save);
  484. }
  485. }
  486. }
  487. // Return validation status
  488. return $status;
  489. }
  490. /**
  491. * Saves the current object. If the object is new, it will be reloaded
  492. * after being saved.
  493. *
  494. * @chainable
  495. * @return ORM
  496. */
  497. public function save()
  498. {
  499. if (empty($this->changed))
  500. return $this;
  501. $data = array();
  502. foreach ($this->changed as $column)
  503. {
  504. // Compile changed data
  505. $data[$column] = $this->object[$column];
  506. }
  507. if ($this->loaded === TRUE)
  508. {
  509. $query = $this->db
  510. ->where($this->primary_key, $this->object[$this->primary_key])
  511. ->update($this->table_name, $data);
  512. // Object has been saved
  513. $this->saved = TRUE;
  514. // Nothing has been changed
  515. $this->changed = array();
  516. }
  517. else
  518. {
  519. $query = $this->db
  520. ->insert($this->table_name, $data);
  521. if ($query->count() > 0)
  522. {
  523. if (empty($this->object[$this->primary_key]))
  524. {
  525. // Load the insert id as the primary key
  526. $this->object[$this->primary_key] = $query->insert_id();
  527. }
  528. // Reload the object
  529. $this->reload();
  530. }
  531. }
  532. return $this;
  533. }
  534. /**
  535. * Deletes the current object from the database. This does NOT destroy
  536. * relationships that have been created with other objects.
  537. *
  538. * @chainable
  539. * @return ORM
  540. */
  541. public function delete($id = NULL)
  542. {
  543. if ($id === NULL AND $this->loaded)
  544. {
  545. // Use the the primary key value
  546. $id = $this->object[$this->primary_key];
  547. }
  548. // Delete this object
  549. $this->db->where($this->primary_key, $id)->delete($this->table_name);
  550. return $this->clear();
  551. }
  552. /**
  553. * Delete all objects in the associated table. This does NOT destroy
  554. * relationships that have been created with other objects.
  555. *
  556. * @chainable
  557. * @param array ids to delete
  558. * @return ORM
  559. */
  560. public function delete_all($ids = NULL)
  561. {
  562. if (is_array($ids))
  563. {
  564. // Delete only given ids
  565. $this->db->in($this->primary_key, $ids);
  566. }
  567. else
  568. {
  569. // Delete all records
  570. $this->db->where(TRUE);
  571. }
  572. // Delete all objects
  573. $this->db->delete($this->table_name);
  574. return $this->clear();
  575. }
  576. /**
  577. * Unloads the current object and clears the status.
  578. *
  579. * @chainable
  580. * @return ORM
  581. */
  582. public function clear()
  583. {
  584. // Object is no longer loaded or saved
  585. $this->loaded = $this->saved = FALSE;
  586. // Nothing has been changed
  587. $this->changed = array();
  588. // Replace the current object with an empty one
  589. $this->load_values(array());
  590. return $this;
  591. }
  592. /**
  593. * Reloads the current object from the database.
  594. *
  595. * @chainable
  596. * @return ORM
  597. */
  598. public function reload()
  599. {
  600. return $this->find($this->object[$this->primary_key]);
  601. }
  602. /**
  603. * Reload column definitions.
  604. *
  605. * @chainable
  606. * @param boolean force reloading
  607. * @return ORM
  608. */
  609. public function reload_columns($force = FALSE)
  610. {
  611. if ($force === TRUE OR empty($this->table_columns))
  612. {
  613. // Load table columns
  614. $this->table_columns = $this->db->list_fields($this->table_name);
  615. if (empty($this->table_columns))
  616. throw new Kohana_Exception('database.table_not_found', $this->table);
  617. }
  618. return $this;
  619. }
  620. /**
  621. * Tests if this object has a relationship to a different model.
  622. *
  623. * @param object related ORM model
  624. * @return boolean
  625. */
  626. public function has(ORM $model)
  627. {
  628. if ( ! $this->loaded)
  629. return FALSE;
  630. if (($join_table = array_search(inflector::plural($model->object_name), $this->has_and_belongs_to_many)) === FALSE)
  631. return FALSE;
  632. if (is_int($join_table))
  633. {
  634. // No "through" table, load the default JOIN table
  635. $join_table = $model->join_table($this->table_name);
  636. }
  637. if ($model->loaded)
  638. {
  639. // Select only objects of a specific id
  640. $this->db->where($model->foreign_key(NULL, $join_table), $model->primary_key_value);
  641. }
  642. // Return the number of rows that exist
  643. return $this->db
  644. ->where($this->foreign_key(NULL, $join_table), $this->object[$this->primary_key])
  645. ->count_records($join_table);
  646. }
  647. /**
  648. * Adds a new relationship to between this model and another.
  649. *
  650. * @param object related ORM model
  651. * @return boolean
  652. */
  653. public function add(ORM $model)
  654. {
  655. if ( ! $this->loaded)
  656. return FALSE;
  657. if ($this->has($model))
  658. return TRUE;
  659. if (($join_table = array_search(inflector::plural($model->object_name), $this->has_and_belongs_to_many)) === FALSE)
  660. return FALSE;
  661. if (is_int($join_table))
  662. {
  663. // No "through" table, load the default JOIN table
  664. $join_table = $model->join_table($this->table_name);
  665. }
  666. // Insert the new relationship
  667. $this->db->insert($join_table, array
  668. (
  669. $this->foreign_key(NULL, $join_table) => $this->object[$this->primary_key],
  670. $model->foreign_key(NULL, $join_table) => $model->primary_key_value,
  671. ));
  672. return TRUE;
  673. }
  674. /**
  675. * Adds a new relationship to between this model and another.
  676. *
  677. * @param object related ORM model
  678. * @return boolean
  679. */
  680. public function remove(ORM $model)
  681. {
  682. if ( ! $this->has($model))
  683. return FALSE;
  684. if (($join_table = array_search(inflector::plural($model->object_name), $this->has_and_belongs_to_many)) === FALSE)
  685. return FALSE;
  686. if (is_int($join_table))
  687. {
  688. // No "through" table, load the default JOIN table
  689. $join_table = $model->join_table($this->table_name);
  690. }
  691. if ($model->loaded)
  692. {
  693. // Delete only a specific object
  694. $this->db->where($model->foreign_key(NULL, $join_table), $model->primary_key_value);
  695. }
  696. // Return the number of rows deleted
  697. return $this->db
  698. ->where($this->foreign_key(NULL, $join_table), $this->object[$this->primary_key])
  699. ->delete($join_table)
  700. ->count();
  701. }
  702. /**
  703. * Count the number of records in the table.
  704. *
  705. * @return integer
  706. */
  707. public function count_all()
  708. {
  709. // Return the total number of records in a table
  710. return $this->db->count_records($this->table_name);
  711. }
  712. /**
  713. * Count the number of records in the last query, without LIMIT or OFFSET applied.
  714. *
  715. * @return integer
  716. */
  717. public function count_last_query()
  718. {
  719. if ($sql = $this->db->last_query())
  720. {
  721. if (stripos($sql, 'LIMIT') !== FALSE)
  722. {
  723. // Remove LIMIT from the SQL
  724. $sql = preg_replace('/\bLIMIT\s+[^a-z]+/i', '', $sql);
  725. }
  726. if (stripos($sql, 'OFFSET') !== FALSE)
  727. {
  728. // Remove OFFSET from the SQL
  729. $sql = preg_replace('/\bOFFSET\s+\d+/i', '', $sql);
  730. }
  731. // Get the total rows from the last query executed
  732. $result = $this->db->query
  733. (
  734. 'SELECT COUNT(*) AS '.$this->db->escape_column('total_rows').' '.
  735. 'FROM ('.trim($sql).') AS '.$this->db->escape_table('counted_results')
  736. );
  737. if ($result->count())
  738. {
  739. // Return the total number of rows from the query
  740. return (int) $result->current()->total_rows;
  741. }
  742. }
  743. return FALSE;
  744. }
  745. /**
  746. * Proxy method to Database list_fields.
  747. *
  748. * @param string table name
  749. * @return array
  750. */
  751. public function list_fields($table)
  752. {
  753. // Proxy to database
  754. return $this->db->list_fields($table);
  755. }
  756. /**
  757. * Proxy method to Database field_data.
  758. *
  759. * @param string table name
  760. * @return array
  761. */
  762. public function field_data($table)
  763. {
  764. // Proxy to database
  765. return $this->db->field_data($table);
  766. }
  767. /**
  768. * Proxy method to Database last_query.
  769. *
  770. * @return string
  771. */
  772. public function last_query()
  773. {
  774. // Proxy to database
  775. return $this->db->last_query();
  776. }
  777. /**
  778. * Proxy method to Database field_data.
  779. *
  780. * @chainable
  781. * @param string SQL query to clear
  782. * @return ORM
  783. */
  784. public function clear_cache($sql = NULL)
  785. {
  786. // Proxy to database
  787. $this->db->clear_cache($sql);
  788. return $this;
  789. }
  790. /**
  791. * Returns the unique key for a specific value. This method is expected
  792. * to be overloaded in models if the model has other unique columns.
  793. *
  794. * @param mixed unique value
  795. * @return string
  796. */
  797. public function unique_key($id)
  798. {
  799. return $this->primary_key;
  800. }
  801. /**
  802. * Determines the name of a foreign key for a specific table.
  803. *
  804. * @param string related table name
  805. * @param string prefix table name (used for JOINs)
  806. * @return string
  807. */
  808. public function foreign_key($table = NULL, $prefix_table = NULL)
  809. {
  810. if ($table === TRUE)
  811. {
  812. // Return the name of this tables PK
  813. return $this->table_name.'.'.$this->primary_key;
  814. }
  815. if (is_string($prefix_table))
  816. {
  817. // Add a period for prefix_table.column support
  818. $prefix_table .= '.';
  819. }
  820. if ( ! is_string($table) OR ! isset($this->object[$table.'_'.$this->primary_key]))
  821. {
  822. // Use this table
  823. $table = $this->table_name;
  824. if ($this->table_names_plural === TRUE)
  825. {
  826. // Make the key name singular
  827. $table = inflector::singular($table);
  828. }
  829. }
  830. return $prefix_table.$table.'_'.$this->primary_key;
  831. }
  832. /**
  833. * This uses alphabetical comparison to choose the name of the table.
  834. *
  835. * Example: The joining table of users and roles would be roles_users,
  836. * because "r" comes before "u". Joining products and categories would
  837. * result in categories_prouducts, because "c" comes before "p".
  838. *
  839. * Example: zoo > zebra > robber > ocean > angel > aardvark
  840. *
  841. * @param string table name
  842. * @return string
  843. */
  844. public function join_table($table)
  845. {
  846. if ($this->table_name > $table)
  847. {
  848. $table = $table.'_'.$this->table_name;
  849. }
  850. else
  851. {
  852. $table = $this->table_name.'_'.$table;
  853. }
  854. return $table;
  855. }
  856. /**
  857. * Loads a value according to the types defined by the column metadata.
  858. *
  859. * @param string column name
  860. * @param mixed value to load
  861. * @return mixed
  862. */
  863. protected function load_type($column, $value)
  864. {
  865. if (is_object($value) OR is_array($value) OR ! isset($this->table_columns[$column]))
  866. return $value;
  867. // Load column data
  868. $column = $this->table_columns[$column];
  869. if ($value === NULL AND ! empty($column['null']))
  870. return $value;
  871. if ( ! empty($column['binary']) AND ! empty($column['exact']) AND (int) $column['length'] === 1)
  872. {
  873. // Use boolean for BINARY(1) fields
  874. $column['type'] = 'boolean';
  875. }
  876. switch ($column['type'])
  877. {
  878. case 'int':
  879. $value = ($value === '' AND ! empty($data['null'])) ? NULL : (int) $value;
  880. break;
  881. case 'float':
  882. $value = (float) $value;
  883. break;
  884. case 'boolean':
  885. $value = (bool) $value;
  886. break;
  887. case 'string':
  888. $value = (string) $value;
  889. break;
  890. }
  891. return $value;
  892. }
  893. /**
  894. * Loads an array of values into into the current object.
  895. *
  896. * @chainable
  897. * @param array values to load
  898. * @return ORM
  899. */
  900. protected function load_values(array $values)
  901. {
  902. // Get the table columns
  903. $columns = array_keys($this->table_columns);
  904. // Make sure all the columns are defined
  905. $this->object += array_combine($columns, array_fill(0, count($columns), NULL));
  906. foreach ($columns as $column)
  907. {
  908. // Value for this column
  909. $value = isset($values[$column]) ? $values[$column] : NULL;
  910. // Set value manually, to avoid triggering changes
  911. $this->object[$column] = $this->load_type($column, $value);
  912. }
  913. return $this;
  914. }
  915. /**
  916. * Loads a database result, either as a new object for this model, or as
  917. * an iterator for multiple rows.
  918. *
  919. * @chainable
  920. * @param boolean return an iterator or load a single row
  921. * @return ORM for single rows
  922. * @return ORM_Iterator for multiple rows
  923. */
  924. protected function load_result($array = FALSE)
  925. {
  926. if ($array === FALSE)
  927. {
  928. // Only fetch 1 record
  929. $this->db->limit(1);
  930. }
  931. if ( ! isset($this->db_applied['select']))
  932. {
  933. // Selete all columns by default
  934. $this->db->select($this->table_name.'.*');
  935. }
  936. // Load the result
  937. $result = $this->db->get($this->table_name);
  938. if ($array === TRUE)
  939. {
  940. // Return an iterated result
  941. return new ORM_Iterator($this, $result);
  942. }
  943. if ($result->count() === 1)
  944. {
  945. // Model is loaded and saved
  946. $this->loaded = $this->saved = TRUE;
  947. // Clear relationships and changed values
  948. $this->related = $this->changed = array();
  949. // Load object values
  950. $this->load_values($result->result(FALSE)->current());
  951. }
  952. else
  953. {
  954. // Clear the object, nothing was found
  955. $this->clear();
  956. }
  957. return $this;
  958. }
  959. } // End ORM