1 <?php
defined('SYSPATH') OR die('No direct access allowed.');
3 * [Object Relational Mapping][ref-orm] (ORM) is a method of abstracting database
4 * access to standard PHP calls. All table rows are represented as model objects,
5 * with object properties representing row data. ORM in Kohana generally follows
6 * the [Active Record][ref-act] pattern.
8 * [ref-orm]: http://wikipedia.org/wiki/Object-relational_mapping
9 * [ref-act]: http://wikipedia.org/wiki/Active_record
11 * $Id: ORM.php 3917 2009-01-21 03:06:22Z zombor $
15 * @copyright (c) 2007-2008 Kohana Team
16 * @license http://kohanaphp.com/license.html
20 // Current relationships
21 protected $has_one = array();
22 protected $belongs_to = array();
23 protected $has_many = array();
24 protected $has_and_belongs_to_many = array();
26 // Relationships that should always be joined
27 protected $load_with = array();
30 protected $object = array();
31 protected $changed = array();
32 protected $related = array();
33 protected $loaded = FALSE;
34 protected $saved = FALSE;
38 protected $object_relations = array();
39 protected $changed_relations = array();
41 // Model table information
42 protected $object_name;
43 protected $object_plural;
44 protected $table_name;
45 protected $table_columns;
46 protected $ignored_columns;
48 // Table primary key and value
49 protected $primary_key = 'id';
50 protected $primary_val = 'name';
52 // Array of foreign key name overloads
53 protected $foreign_key = array();
55 // Model configuration
56 protected $table_names_plural = TRUE;
57 protected $reload_on_wakeup = TRUE;
59 // Database configuration
60 protected $db = 'default';
61 protected $db_applied = array();
63 // With calls already applied
64 protected $with_applied = array();
66 // Stores column information for ORM models
67 protected static $column_cache = array();
70 * Creates and returns a new model.
73 * @param string model name
74 * @param mixed parameter for find()
77 public static function factory($model, $id = NULL)
80 $model = ucfirst($model).'_Model';
82 return new $model($id);
86 * Prepares the model database connection and loads the object.
88 * @param mixed parameter for find or object to load
91 public function __construct($id = NULL)
93 // Set the object name and plural name
94 $this->object_name
= strtolower(substr(get_class($this), 0, -6));
95 $this->object_plural
= inflector
::plural($this->object_name
);
97 if (!isset($this->sorting
))
100 $this->sorting
= array($this->primary_key
=> 'asc');
103 // Initialize database
104 $this->__initialize();
112 $this->load_values((array) $id);
122 * Prepares the model database connection, determines the table name,
123 * and loads column information.
127 public function __initialize()
129 if ( ! is_object($this->db
))
131 // Get database instance
132 $this->db
= Database
::instance($this->db
);
135 if (empty($this->table_name
))
137 // Table name is the same as the object name
138 $this->table_name
= $this->object_name
;
140 if ($this->table_names_plural
=== TRUE)
142 // Make the table name plural
143 $this->table_name
= inflector
::plural($this->table_name
);
147 if (is_array($this->ignored_columns
))
149 // Make the ignored columns mirrored = mirrored
150 $this->ignored_columns
= array_combine($this->ignored_columns
, $this->ignored_columns
);
153 // Load column information
154 $this->reload_columns();
158 * Allows serialization of only the object data and state, to prevent
159 * "stale" objects being unserialized, which also requires less memory.
163 public function __sleep()
165 // Store only information about the object
166 return array('object_name', 'object', 'changed', 'loaded', 'saved', 'sorting');
170 * Prepares the database connection and reloads the object.
174 public function __wakeup()
176 // Initialize database
177 $this->__initialize();
179 if ($this->reload_on_wakeup
=== TRUE)
187 * Handles pass-through to database methods. Calls to query methods
188 * (query, get, insert, update) are not allowed. Query builder methods
191 * @param string method name
192 * @param array method arguments
195 public function __call($method, array $args)
197 if (method_exists($this->db
, $method))
199 if (in_array($method, array('query', 'get', 'insert', 'update', 'delete')))
200 throw new Kohana_Exception('orm.query_methods_not_allowed');
202 // Method has been applied to the database
203 $this->db_applied
[$method] = $method;
205 // Number of arguments passed
206 $num_args = count($args);
208 if ($method === 'select' AND $num_args > 3)
210 // Call select() manually to avoid call_user_func_array
211 $this->db
->select($args);
215 // We use switch here to manually call the database methods. This is
216 // done for speed: call_user_func_array can take over 300% longer to
217 // make calls. Most database methods are 4 arguments or less, so this
218 // avoids almost any calls to call_user_func_array.
223 // Support for things like reset_select, reset_write, list_tables
224 return $this->db
->$method();
227 $this->db
->$method($args[0]);
230 $this->db
->$method($args[0], $args[1]);
233 $this->db
->$method($args[0], $args[1], $args[2]);
236 $this->db
->$method($args[0], $args[1], $args[2], $args[3]);
239 // Here comes the snail...
240 call_user_func_array(array($this->db
, $method), $args);
249 throw new Kohana_Exception('core.invalid_method', $method, get_class($this));
254 * Handles retrieval of all model values, relationships, and metadata.
256 * @param string column name
259 public function __get($column)
261 if (isset($this->ignored_columns
[$column]))
265 elseif (array_key_exists($column, $this->object))
267 return $this->object[$column];
269 elseif (isset($this->related
[$column]))
271 return $this->related
[$column];
273 elseif ($column === 'primary_key_value')
275 return $this->object[$this->primary_key
];
277 elseif ($model = $this->related_object($column))
279 // This handles the has_one and belongs_to relationships
281 if (array_key_exists($column.'_'.$model->primary_key
, $this->object))
283 // Use the FK that exists in this model as the PK
284 $where = array($model->table_name
.'.'.$model->primary_key
=> $this->object[$column.'_'.$model->primary_key
]);
288 // Use this model PK as the FK
289 $where = array($this->foreign_key() => $this->object[$this->primary_key
]);
292 // one<>alias:one relationship
293 return $this->related
[$column] = $model->find($where);
295 elseif (isset($this->has_many
[$column]))
297 // Load the "middle" model
298 $through = ORM
::factory(inflector
::singular($this->has_many
[$column]));
300 // Load the "end" model
301 $model = ORM
::factory(inflector
::singular($column));
304 $join_table = $through->table_name
;
305 $join_col1 = $model->foreign_key(NULL, $join_table);
306 $join_col2 = $model->foreign_key(TRUE);
308 // one<>alias:many relationship
309 return $this->related
[$column] = $model
310 ->join($join_table, $join_col1, $join_col2)
311 ->where($this->foreign_key(NULL, $join_table), $this->object[$this->primary_key
])
314 elseif (in_array($column, $this->has_many
))
316 // one<>many relationship
317 return $this->related
[$column] = ORM
::factory(inflector
::singular($column))
318 ->where($this->foreign_key($column), $this->object[$this->primary_key
])
321 elseif (in_array($column, $this->has_and_belongs_to_many
))
323 // Load the remote model, always singular
324 $model = ORM
::factory(inflector
::singular($column));
326 if ($this->has($model, TRUE))
328 // many<>many relationship
329 return $this->related
[$column] = $model
330 ->in($model->table_name
.'.'.$model->primary_key
, $this->changed_relations
[$column])
335 // empty many<>many relationship
336 return $this->related
[$column] = $model
337 ->where($model->table_name
.'.'.$model->primary_key
, NULL)
341 elseif (in_array($column, array
343 'object_name', 'object_plural', // Object
344 'primary_key', 'primary_val', 'table_name', 'table_columns', // Table
345 'loaded', 'saved', // Status
346 'has_one', 'belongs_to', 'has_many', 'has_and_belongs_to_many', 'load_with' // Relationships
349 // Model meta information
350 return $this->$column;
354 throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
359 * Handles setting of all model values, and tracks changes between values.
361 * @param string column name
362 * @param mixed column value
365 public function __set($column, $value)
367 if (isset($this->ignored_columns
[$column]))
371 elseif (isset($this->object[$column]) OR array_key_exists($column, $this->object))
373 if (isset($this->table_columns
[$column]))
376 $this->changed
[$column] = $column;
378 // Object is no longer saved
379 $this->saved
= FALSE;
382 $this->object[$column] = $this->load_type($column, $value);
384 elseif (in_array($column, $this->has_and_belongs_to_many
) AND is_array($value))
387 $model = ORM
::factory(inflector
::singular($column));
389 if ( ! isset($this->object_relations
[$column]))
395 // Change the relationships
396 $this->changed_relations
[$column] = $value;
398 if (isset($this->related
[$column]))
400 // Force a reload of the relationships
401 unset($this->related
[$column]);
406 throw new Kohana_Exception('core.invalid_property', $column, get_class($this));
411 * Checks if object data is set.
413 * @param string column name
416 public function __isset($column)
418 return (isset($this->object[$column]) OR isset($this->related
[$column]));
422 * Unsets object data.
424 * @param string column name
427 public function __unset($column)
429 unset($this->object[$column], $this->changed
[$column], $this->related
[$column]);
433 * Displays the primary key of a model when it is converted to a string.
437 public function __toString()
439 return (string) $this->object[$this->primary_key
];
443 * Returns the values of this object as an array.
447 public function as_array()
451 foreach ($this->object as $key => $val)
453 // Reconstruct the array (calls __get)
454 $object[$key] = $this->$key;
461 * Binds another one-to-one object to this model. One-to-one objects
462 * can be nested using 'object1:object2' syntax
464 * @param string $object
467 public function with($object)
469 if (isset($this->with_applied
[$object]))
471 // Don't join anything already joined
475 $prefix = $table = $object;
477 // Split object parts
478 $objects = explode(':', $object);
480 foreach ($objects as $object_part)
482 // Go down the line of objects to find the given target
484 $object = $parent->related_object($object_part);
488 // Can't find related object
493 $table = $object_part;
495 if ($this->table_names_plural
)
497 $table = inflector
::plural($table);
500 // Pop-off top object to get the parent object (user:photo:tag's parent is user:photo)
502 $parent_prefix = implode(':', $objects);
504 if (empty($parent_prefix))
506 // Use this table name itself for the parent prefix
507 $parent_prefix = $this->table_name
;
511 if( ! isset($this->with_applied
[$parent_prefix]))
513 // If the parent object hasn't been joined yet, do it first (otherwise LEFT JOINs fail)
514 $this->with($parent_prefix);
518 // Add to with_applied to prevent duplicate joins
519 $this->with_applied
[$prefix] = TRUE;
521 // Use the keys of the empty object to determine the columns
522 $select = array_keys($object->as_array());
523 foreach ($select as $i => $column)
525 // Add the prefix so that load_result can determine the relationship
526 $select[$i] = $prefix.'.'.$column.' AS '.$prefix.':'.$column;
529 // Select all of the prefixed keys in the object
530 $this->db
->select($select);
532 // Use last object part to generate foreign key
533 $foreign_key = $object_part.'_'.$object->primary_key
;
535 if (array_key_exists($foreign_key, $parent->object))
537 // Foreign key exists in the joined object's parent
538 $join_col1 = $object->foreign_key(TRUE, $prefix);
539 $join_col2 = $parent_prefix.'.'.$foreign_key;
543 $join_col1 = $parent->foreign_key(NULL, $prefix);
544 $join_col2 = $parent_prefix.'.'.$parent->primary_key
;
547 // Join the related object into the result
548 $this->db
->join($object->table_name
.' AS '.$this->db
->table_prefix().$prefix, $join_col1, $join_col2, 'LEFT');
554 * Finds and loads a single database row into the object.
557 * @param mixed primary key or an array of clauses
560 public function find($id = NULL)
566 // Search for all clauses
567 $this->db
->where($id);
571 // Search for a specific column
572 $this->db
->where($this->table_name
.'.'.$this->unique_key($id), $id);
576 return $this->load_result();
580 * Finds multiple database rows and returns an iterator of the rows found.
583 * @param integer SQL limit
584 * @param integer SQL offset
585 * @return ORM_Iterator
587 public function find_all($limit = NULL, $offset = NULL)
589 if ($limit !== NULL AND ! isset($this->db_applied
['limit']))
592 $this->limit($limit);
595 if ($offset !== NULL AND ! isset($this->db_applied
['offset']))
598 $this->offset($offset);
601 return $this->load_result(TRUE);
605 * Creates a key/value array from all of the objects available. Uses find_all
606 * to find the objects.
608 * @param string key column
609 * @param string value column
612 public function select_list($key = NULL, $val = NULL)
616 $key = $this->primary_key
;
621 $val = $this->primary_val
;
624 // Return a select list from the results
625 return $this->select($key, $val)->find_all()->select_list($key, $val);
629 * Validates the current object. This method should generally be called
630 * via the model, after the $_POST Validation object has been created.
632 * @param object Validation array
635 public function validate(Validation
$array, $save = FALSE)
637 if ( ! $array->submitted())
639 $safe_array = $array->safe_array();
641 foreach ($safe_array as $key => $value)
643 // Get the value from this object
644 $value = $this->$key;
646 if (is_object($value) AND $value instanceof ORM_Iterator
)
648 // Convert the value to an array of primary keys
649 $value = $value->primary_key_array();
653 $array[$key] = $value;
657 // Validate the array
658 if ($status = $array->validate())
660 $safe_array = $array->safe_array();
662 foreach ($safe_array as $key => $value)
665 $this->$key = $value;
668 if ($save === TRUE OR is_string($save))
673 if (is_string($save))
675 // Redirect to the saved page
676 return url
::redirect($save);
681 // Return validation status
686 * Saves the current object.
691 public function save()
693 if ( ! empty($this->changed
))
696 foreach ($this->changed
as $column)
698 // Compile changed data
699 $data[$column] = $this->object[$column];
702 if ($this->loaded
=== TRUE)
705 ->where($this->primary_key
, $this->object[$this->primary_key
])
706 ->update($this->table_name
, $data);
708 // Object has been saved
714 ->insert($this->table_name
, $data);
716 if ($query->count() > 0)
718 if (empty($this->object[$this->primary_key
]))
720 // Load the insert id as the primary key
721 $this->object[$this->primary_key
] = $query->insert_id();
724 // Object is now loaded and saved
725 $this->loaded
= $this->saved
= TRUE;
729 if ($this->saved
=== TRUE)
731 // All changes have been saved
732 $this->changed
= array();
736 if ($this->saved
=== TRUE AND ! empty($this->changed_relations
))
738 foreach ($this->changed_relations
as $column => $values)
740 // All values that were added
741 $added = array_diff($values, $this->object_relations
[$column]);
743 // All values that were saved
744 $removed = array_diff($this->object_relations
[$column], $values);
746 if (empty($added) AND empty($removed))
752 // Clear related columns
753 unset($this->related
[$column]);
756 $model = ORM
::factory(inflector
::singular($column));
758 if (($join_table = array_search($column, $this->has_and_belongs_to_many
)) === FALSE)
761 if (is_int($join_table))
763 // No "through" table, load the default JOIN table
764 $join_table = $model->join_table($this->table_name
);
767 // Foreign keys for the join table
768 $object_fk = $this->foreign_key(NULL);
769 $related_fk = $model->foreign_key(NULL);
771 if ( ! empty($added))
773 foreach ($added as $id)
775 // Insert the new relationship
776 $this->db
->insert($join_table, array
778 $object_fk => $this->object[$this->primary_key
],
784 if ( ! empty($removed))
787 ->where($object_fk, $this->object[$this->primary_key
])
788 ->in($related_fk, $removed)
789 ->delete($join_table);
792 // Clear all relations for this column
793 unset($this->object_relations
[$column], $this->changed_relations
[$column]);
801 * Deletes the current object from the database. This does NOT destroy
802 * relationships that have been created with other objects.
807 public function delete($id = NULL)
809 if ($id === NULL AND $this->loaded
)
811 // Use the the primary key value
812 $id = $this->object[$this->primary_key
];
815 // Delete this object
816 $this->db
->where($this->primary_key
, $id)->delete($this->table_name
);
818 return $this->clear();
822 * Delete all objects in the associated table. This does NOT destroy
823 * relationships that have been created with other objects.
826 * @param array ids to delete
829 public function delete_all($ids = NULL)
833 // Delete only given ids
834 $this->db
->in($this->primary_key
, $ids);
836 elseif (is_null($ids))
838 // Delete all records
839 $this->db
->where(TRUE);
843 // Do nothing - safeguard
847 // Delete all objects
848 $this->db
->delete($this->table_name
);
850 return $this->clear();
854 * Unloads the current object and clears the status.
859 public function clear()
861 // Create an array with all the columns set to NULL
862 $columns = array_keys($this->table_columns
);
863 $values = array_combine($columns, array_fill(0, count($columns), NULL));
865 // Replace the current object with an empty one
866 $this->load_values($values);
872 * Reloads the current object from the database.
877 public function reload()
879 return $this->find($this->object[$this->primary_key
]);
883 * Reload column definitions.
886 * @param boolean force reloading
889 public function reload_columns($force = FALSE)
891 if ($force === TRUE OR empty($this->table_columns
))
893 if (isset(self
::$column_cache[$this->object_name
]))
895 // Use cached column information
896 $this->table_columns
= self
::$column_cache[$this->object_name
];
900 // Load table columns
901 self
::$column_cache[$this->object_name
] = $this->table_columns
= $this->db
->list_fields($this->table_name
, TRUE);
909 * Tests if this object has a relationship to a different model.
911 * @param object related ORM model
912 * @param boolean check for any relations to given model
915 public function has(ORM
$model, $any = FALSE)
917 $related = $model->object_plural
;
919 if (($join_table = array_search($related, $this->has_and_belongs_to_many
)) === FALSE)
922 if (is_int($join_table))
924 // No "through" table, load the default JOIN table
925 $join_table = $model->join_table($this->table_name
);
928 if ( ! isset($this->object_relations
[$related]))
930 // Load the object relationships
931 $this->changed_relations
[$related] = $this->object_relations
[$related] = $this->load_relations($join_table, $model);
934 if ( ! $model->empty_primary_key())
936 // Check if a specific object exists
937 return in_array($model->primary_key_value
, $this->changed_relations
[$related]);
941 // Check if any relations to given model exist
942 return ! empty($this->changed_relations
[$related]);
951 * Adds a new relationship to between this model and another.
953 * @param object related ORM model
956 public function add(ORM
$model)
958 if ($this->has($model))
961 // Get the faked column name
962 $column = $model->object_plural
;
964 // Add the new relation to the update
965 $this->changed_relations
[$column][] = $model->primary_key_value
;
967 if (isset($this->related
[$column]))
969 // Force a reload of the relationships
970 unset($this->related
[$column]);
977 * Adds a new relationship to between this model and another.
979 * @param object related ORM model
982 public function remove(ORM
$model)
984 if ( ! $this->has($model))
987 // Get the faked column name
988 $column = $model->object_plural
;
990 if (($key = array_search($model->primary_key_value
, $this->changed_relations
[$column])) === FALSE)
993 // Remove the relationship
994 unset($this->changed_relations
[$column][$key]);
996 if (isset($this->related
[$column]))
998 // Force a reload of the relationships
999 unset($this->related
[$column]);
1006 * Count the number of records in the table.
1010 public function count_all()
1012 // Return the total number of records in a table
1013 return $this->db
->count_records($this->table_name
);
1017 * Count the number of records in the last query, without LIMIT or OFFSET applied.
1021 public function count_last_query()
1023 if ($sql = $this->db
->last_query())
1025 if (stripos($sql, 'LIMIT') !== FALSE)
1027 // Remove LIMIT from the SQL
1028 $sql = preg_replace('/\sLIMIT\s+[^a-z]+/i', ' ', $sql);
1031 if (stripos($sql, 'OFFSET') !== FALSE)
1033 // Remove OFFSET from the SQL
1034 $sql = preg_replace('/\sOFFSET\s+\d+/i', '', $sql);
1037 // Get the total rows from the last query executed
1038 $result = $this->db
->query
1040 'SELECT COUNT(*) AS '.$this->db
->escape_column('total_rows').' '.
1041 'FROM ('.trim($sql).') AS '.$this->db
->escape_table('counted_results')
1044 // Return the total number of rows from the query
1045 return (int) $result->current()->total_rows
;
1052 * Proxy method to Database list_fields.
1054 * @param string table name
1057 public function list_fields($table)
1059 // Proxy to database
1060 return $this->db
->list_fields($table);
1064 * Proxy method to Database field_data.
1066 * @param string table name
1069 public function field_data($table)
1071 // Proxy to database
1072 return $this->db
->field_data($table);
1076 * Proxy method to Database last_query.
1080 public function last_query()
1082 // Proxy to database
1083 return $this->db
->last_query();
1087 * Proxy method to Database field_data.
1090 * @param string SQL query to clear
1093 public function clear_cache($sql = NULL)
1095 // Proxy to database
1096 $this->db
->clear_cache($sql);
1102 * Returns the unique key for a specific value. This method is expected
1103 * to be overloaded in models if the model has other unique columns.
1105 * @param mixed unique value
1108 public function unique_key($id)
1110 return $this->primary_key
;
1114 * Determines the name of a foreign key for a specific table.
1116 * @param string related table name
1117 * @param string prefix table name (used for JOINs)
1120 public function foreign_key($table = NULL, $prefix_table = NULL)
1122 if ($table === TRUE)
1124 if (is_string($prefix_table))
1126 // Use prefix table name and this table's PK
1127 return $prefix_table.'.'.$this->primary_key
;
1131 // Return the name of this table's PK
1132 return $this->table_name
.'.'.$this->primary_key
;
1136 if (is_string($prefix_table))
1138 // Add a period for prefix_table.column support
1139 $prefix_table .= '.';
1142 if (isset($this->foreign_key
[$table]))
1144 // Use the defined foreign key name, no magic here!
1145 $foreign_key = $this->foreign_key
[$table];
1149 if ( ! is_string($table) OR ! isset($this->object[$table.'_'.$this->primary_key
]))
1152 $table = $this->table_name
;
1154 if (strpos($table, '.') !== FALSE)
1156 // Hack around support for PostgreSQL schemas
1157 list ($schema, $table) = explode('.', $table, 2);
1160 if ($this->table_names_plural
=== TRUE)
1162 // Make the key name singular
1163 $table = inflector
::singular($table);
1167 $foreign_key = $table.'_'.$this->primary_key
;
1170 return $prefix_table.$foreign_key;
1174 * This uses alphabetical comparison to choose the name of the table.
1176 * Example: The joining table of users and roles would be roles_users,
1177 * because "r" comes before "u". Joining products and categories would
1178 * result in categories_products, because "c" comes before "p".
1180 * Example: zoo > zebra > robber > ocean > angel > aardvark
1182 * @param string table name
1185 public function join_table($table)
1187 if ($this->table_name
> $table)
1189 $table = $table.'_'.$this->table_name
;
1193 $table = $this->table_name
.'_'.$table;
1200 * Returns an ORM model for the given object name;
1202 * @param string object name
1205 protected function related_object($object)
1207 if (isset($this->has_one
[$object]))
1209 $object = ORM
::factory($this->has_one
[$object]);
1211 elseif (isset($this->belongs_to
[$object]))
1213 $object = ORM
::factory($this->belongs_to
[$object]);
1215 elseif (in_array($object, $this->has_one
) OR in_array($object, $this->belongs_to
))
1217 $object = ORM
::factory($object);
1228 * Loads an array of values into into the current object.
1231 * @param array values to load
1234 public function load_values(array $values)
1236 if (array_key_exists($this->primary_key
, $values))
1238 // Replace the object and reset the object status
1239 $this->object = $this->changed
= $this->related
= array();
1241 // Set the loaded and saved object status based on the primary key
1242 $this->loaded
= $this->saved
= ($values[$this->primary_key
] !== NULL);
1248 foreach ($values as $column => $value)
1250 if (strpos($column, ':') === FALSE)
1252 if (isset($this->table_columns
[$column]))
1254 // The type of the value can be determined, convert the value
1255 $value = $this->load_type($column, $value);
1258 $this->object[$column] = $value;
1262 list ($prefix, $column) = explode(':', $column, 2);
1264 $related[$prefix][$column] = $value;
1268 if ( ! empty($related))
1270 foreach ($related as $object => $values)
1272 // Load the related objects with the values in the result
1273 $this->related
[$object] = $this->related_object($object)->load_values($values);
1281 * Loads a value according to the types defined by the column metadata.
1283 * @param string column name
1284 * @param mixed value to load
1287 protected function load_type($column, $value)
1289 if (is_object($value) OR is_array($value) OR ! isset($this->table_columns
[$column]))
1293 $column = $this->table_columns
[$column];
1295 if ($value === NULL AND ! empty($column['null']))
1298 if ( ! empty($column['binary']) AND ! empty($column['exact']) AND (int) $column['length'] === 1)
1300 // Use boolean for BINARY(1) fields
1301 $column['type'] = 'boolean';
1304 switch ($column['type'])
1307 if ($value === '' AND ! empty($column['null']))
1309 // Forms will only submit strings, so empty integer values must be null
1312 elseif ((float) $value > PHP_INT_MAX
)
1314 // This number cannot be represented by a PHP integer, so we convert it to a string
1315 $value = (string) $value;
1319 $value = (int) $value;
1323 $value = (float) $value;
1326 $value = (bool) $value;
1329 $value = (string) $value;
1337 * Loads a database result, either as a new object for this model, or as
1338 * an iterator for multiple rows.
1341 * @param boolean return an iterator or load a single row
1342 * @return ORM for single rows
1343 * @return ORM_Iterator for multiple rows
1345 protected function load_result($array = FALSE)
1347 if ($array === FALSE)
1349 // Only fetch 1 record
1350 $this->db
->limit(1);
1353 if ( ! isset($this->db_applied
['select']))
1355 // Select all columns by default
1356 $this->db
->select($this->table_name
.'.*');
1359 if ( ! empty($this->load_with
))
1361 foreach ($this->load_with
as $object)
1363 // Join each object into the results
1364 $this->with($object);
1368 if ( ! isset($this->db_applied
['orderby']) AND ! empty($this->sorting
))
1371 foreach ($this->sorting
as $column => $direction)
1373 if (strpos($column, '.') === FALSE)
1375 // Keeps sorting working properly when using JOINs on
1376 // tables with columns of the same name
1377 $column = $this->table_name
.'.'.$column;
1380 $sorting[$column] = $direction;
1383 // Apply the user-defined sorting
1384 $this->db
->orderby($sorting);
1388 $result = $this->db
->get($this->table_name
);
1390 if ($array === TRUE)
1392 // Return an iterated result
1393 return new ORM_Iterator($this, $result);
1396 if ($result->count() === 1)
1398 // Load object values
1399 $this->load_values($result->result(FALSE)->current());
1403 // Clear the object, nothing was found
1411 * Return an array of all the primary keys of the related table.
1413 * @param string table name
1414 * @param object ORM model to find relations of
1417 protected function load_relations($table, ORM
$model)
1419 // Save the current query chain (otherwise the next call will clash)
1423 ->select($model->foreign_key(NULL).' AS id')
1425 ->where($this->foreign_key(NULL, $table), $this->object[$this->primary_key
])
1431 $relations = array();
1432 foreach ($query as $row)
1434 $relations[] = $row->id
;
1441 * Returns whether or not primary key is empty
1445 protected function empty_primary_key()
1447 return (empty($this->object[$this->primary_key
]) AND $this->object[$this->primary_key
] !== '0');