Modules

ORM
extends Kohana_ORM

Object Relational Mapping (ORM) is a method of abstracting database access to standard PHP calls. All table rows are represented as model objects, with object properties representing row data. ORM in Kohana generally follows the Active Record pattern.

$Id: ORM.php 4427 2009-06-19 23:31:36Z jheathco $

package
Kohana/ORM
category
Base
author
Kohana Team
copyright
© 2007-2010 Kohana Team
license
http://kohanaframework.org/license

Class declared in MODPATH/orm/classes/orm.php on line 3.

Properties

protected array $_belongs_to

Array of belongs to relationships. See Relationships for usage.

protected $_callbacks

protected $_changed

protected static $_column_cache

array(0) 

protected $_created_column

protected $_db

protected $_db_applied

protected $_db_builder

protected static $_db_methods

array(29) (
    0 => string(5) "where"
    1 => string(9) "and_where"
    2 => string(8) "or_where"
    3 => string(10) "where_open"
    4 => string(14) "and_where_open"
    5 => string(13) "or_where_open"
    6 => string(11) "where_close"
    7 => string(15) "and_where_close"
    8 => string(14) "or_where_close"
    9 => string(8) "distinct"
    10 => string(6) "select"
    11 => string(4) "from"
    12 => string(4) "join"
    13 => string(2) "on"
    14 => string(8) "group_by"
    15 => string(6) "having"
    16 => string(10) "and_having"
    17 => string(9) "or_having"
    18 => string(11) "having_open"
    19 => string(15) "and_having_open"
    20 => string(14) "or_having_open"
    21 => string(12) "having_close"
    22 => string(16) "and_having_close"
    23 => string(15) "or_having_close"
    24 => string(8) "order_by"
    25 => string(5) "limit"
    26 => string(6) "offset"
    27 => string(6) "cached"
    28 => string(16) "count_last_query"
    5357877594258 => bool TRUE
)

protected $_db_pending

protected $_db_reset

protected $_filters

protected $_foreign_key_suffix

protected $_has_many

protected $_has_one

protected $_ignored_columns

protected $_labels

protected $_load_with

protected $_loaded

protected $_object

protected $_object_name

protected $_object_plural

protected $_preload_data

protected $_primary_key

protected $_primary_val

protected static $_properties

array(18) (
    0 => string(11) "object_name"
    1 => string(13) "object_plural"
    2 => string(6) "loaded"
    3 => string(5) "saved"
    4 => string(11) "primary_key"
    5 => string(11) "primary_val"
    6 => string(10) "table_name"
    7 => string(13) "table_columns"
    8 => string(7) "has_one"
    9 => string(10) "belongs_to"
    10 => string(8) "has_many"
    11 => string(16) "has_many_through"
    12 => string(9) "load_with"
    13 => string(8) "validate"
    14 => string(5) "rules"
    15 => string(9) "callbacks"
    16 => string(7) "filters"
    17 => string(6) "labels"
    5357877594258 => bool TRUE
)

protected $_reload_on_wakeup

protected $_rules

protected $_saved

protected $_sorting

protected $_table_columns

protected $_table_name

protected $_table_names_plural

protected $_updated_column

protected $_validate

protected $_with_applied

Methods

public __call( string $method , array $args ) (defined in Kohana_ORM)

Handles pass-through to database methods. Calls to query methods (query, get, insert, update) are not allowed. Query builder methods are chainable.

Parameters

  • string $method required - Method name
  • array $args required - Method arguments

Return Values

  • mixed

Source Code

public function __call($method, array $args)
{
	if (in_array($method, ORM::$_properties))
	{
		if ($method === 'loaded')
		{
			if ( ! isset($this->_object_name))
			{
				// Calling loaded method prior to the object being fully initialized
				return FALSE;
			}

			$this->_load();
		}
		elseif ($method === 'validate')
		{
			if ( ! isset($this->_validate))
			{
				// Initialize the validation object
				$this->_validate();
			}
		}

		// Return the property
		return $this->{'_'.$method};
	}
	elseif (in_array($method, ORM::$_db_methods))
	{
		// Add pending database call which is executed after query type is determined
		$this->_db_pending[] = array('name' => $method, 'args' => $args);

		return $this;
	}
	else
	{
		throw new Kohana_Exception('Invalid method :method called in :class',
			array(':method' => $method, ':class' => get_class($this)));
	}
}

public __construct( [ mixed $id = NULL ] ) (defined in Kohana_ORM)

Prepares the model database connection and loads the object.

Parameters

  • mixed $id = NULL - Parameter for find or object to load

Return Values

  • void

Source Code

public function __construct($id = NULL)
{
	// Set the object name and plural name
	$this->_object_name   = strtolower(substr(get_class($this), 6));
	$this->_object_plural = Inflector::plural($this->_object_name);

	if ( ! isset($this->_sorting))
	{
		// Default sorting
		$this->_sorting = array($this->_primary_key => 'ASC');
	}

	if ( ! empty($this->_ignored_columns))
	{
		// Optimize for performance
		$this->_ignored_columns = array_combine($this->_ignored_columns, $this->_ignored_columns);
	}

	// Initialize database
	$this->_initialize();

	// Clear the object
	$this->clear();

	if ($id !== NULL)
	{
		if (is_array($id))
		{
			foreach ($id as $column => $value)
			{
				// Passing an array of column => values
				$this->where($column, '=', $value);
			}

			$this->find();
		}
		else
		{
			// Passing the primary key

			// Set the object's primary key, but don't load it until needed
			$this->_object[$this->_primary_key] = $id;

			// Object is considered saved until something is set
			$this->_saved = TRUE;
		}
	}
	elseif ( ! empty($this->_preload_data))
	{
		// Load preloaded data from a database call cast
		$this->_load_values($this->_preload_data);

		$this->_preload_data = array();
	}
}

public __get( string $column ) (defined in Kohana_ORM)

Handles retrieval of all model values, relationships, and metadata.

Parameters

  • string $column required - Column name

Return Values

  • mixed

Source Code

public function __get($column)
{
	if (array_key_exists($column, $this->_object))
	{
		$this->_load();

		return $this->_object[$column];
	}
	elseif (isset($this->_related[$column]) AND $this->_related[$column]->_loaded)
	{
		// Return related model that has already been loaded
		return $this->_related[$column];
	}
	elseif (isset($this->_belongs_to[$column]))
	{
		$this->_load();

		$model = $this->_related($column);

		// Use this model's column and foreign model's primary key
		$col = $model->_table_name.'.'.$model->_primary_key;
		$val = $this->_object[$this->_belongs_to[$column]['foreign_key']];

		$model->where($col, '=', $val)->find();

		return $this->_related[$column] = $model;
	}
	elseif (isset($this->_has_one[$column]))
	{
		$model = $this->_related($column);

		// Use this model's primary key value and foreign model's column
		$col = $model->_table_name.'.'.$this->_has_one[$column]['foreign_key'];
		$val = $this->pk();

		$model->where($col, '=', $val)->find();

		return $this->_related[$column] = $model;
	}
	elseif (isset($this->_has_many[$column]))
	{
		$model = ORM::factory($this->_has_many[$column]['model']);

		if (isset($this->_has_many[$column]['through']))
		{
			// Grab has_many "through" relationship table
			$through = $this->_has_many[$column]['through'];

			// Join on through model's target foreign key (far_key) and target model's primary key
			$join_col1 = $through.'.'.$this->_has_many[$column]['far_key'];
			$join_col2 = $model->_table_name.'.'.$model->_primary_key;

			$model->join($through)->on($join_col1, '=', $join_col2);

			// Through table's source foreign key (foreign_key) should be this model's primary key
			$col = $through.'.'.$this->_has_many[$column]['foreign_key'];
			$val = $this->pk();
		}
		else
		{
			// Simple has_many relationship, search where target model's foreign key is this model's primary key
			$col = $model->_table_name.'.'.$this->_has_many[$column]['foreign_key'];
			$val = $this->pk();
		}

		return $model->where($col, '=', $val);
	}
	else
	{
		throw new Kohana_Exception('The :property property does not exist in the :class class',
			array(':property' => $column, ':class' => get_class($this)));
	}
}

public __isset( string $column ) (defined in Kohana_ORM)

Checks if object data is set.

Parameters

  • string $column required - Column name

Return Values

  • boolean

Source Code

public function __isset($column)
{
	$this->_load();

	return
	(
		isset($this->_object[$column]) OR
		isset($this->_related[$column]) OR
		isset($this->_has_one[$column]) OR
		isset($this->_belongs_to[$column]) OR
		isset($this->_has_many[$column])
	);
}

public __set( string $column , mixed $value ) (defined in Kohana_ORM)

Handles setting of all model values, and tracks changes between values.

Parameters

  • string $column required - Column name
  • mixed $value required - Column value

Return Values

  • void

Source Code

public function __set($column, $value)
{
	if ( ! isset($this->_object_name))
	{
		// Object not yet constructed, so we're loading data from a database call cast
		$this->_preload_data[$column] = $value;

		return;
	}

	if (array_key_exists($column, $this->_ignored_columns))
	{
		// No processing for ignored columns, just store it
		$this->_object[$column] = $value;
	}
	elseif (array_key_exists($column, $this->_object))
	{
		$this->_object[$column] = $value;

		if (isset($this->_table_columns[$column]))
		{
			// Data has changed
			$this->_changed[$column] = $column;

			// Object is no longer saved
			$this->_saved = FALSE;
		}
	}
	elseif (isset($this->_belongs_to[$column]))
	{
		// Update related object itself
		$this->_related[$column] = $value;

		// Update the foreign key of this model
		$this->_object[$this->_belongs_to[$column]['foreign_key']] = $value->pk();

		$this->_changed[$column] = $this->_belongs_to[$column]['foreign_key'];
	}
	else
	{
		throw new Kohana_Exception('The :property: property does not exist in the :class: class',
			array(':property:' => $column, ':class:' => get_class($this)));
	}
}

public __sleep( ) (defined in Kohana_ORM)

Allows serialization of only the object data and state, to prevent "stale" objects being unserialized, which also requires less memory.

Return Values

  • array

Source Code

public function __sleep()
{
	// Store only information about the object
	return array('_object_name', '_object', '_changed', '_loaded', '_saved', '_sorting', '_ignored_columns');
}

public __toString( ) (defined in Kohana_ORM)

Displays the primary key of a model when it is converted to a string.

Return Values

  • string

Source Code

public function __toString()
{
	return (string) $this->pk();
}

public __unset( string $column ) (defined in Kohana_ORM)

Unsets object data.

Parameters

  • string $column required - Column name

Return Values

  • void

Source Code

public function __unset($column)
{
	$this->_load();

	unset($this->_object[$column], $this->_changed[$column], $this->_related[$column]);
}

public __wakeup( ) (defined in Kohana_ORM)

Prepares the database connection and reloads the object.

Return Values

  • void

Source Code

public function __wakeup()
{
	// Initialize database
	$this->_initialize();

	if ($this->_reload_on_wakeup === TRUE)
	{
		// Reload the object
		$this->reload();
	}
}

public add( string $alias , ORM $model [, array $data = NULL ] ) (defined in Kohana_ORM)

Adds a new relationship to between this model and another.

Parameters

  • string $alias required - Alias of the has_many "through" relationship
  • ORM $model required - Related ORM model
  • array $data = NULL - Additional data to store in "through"/pivot table

Return Values

  • ORM

Source Code

public function add($alias, ORM $model, $data = NULL)
{
	$columns = array($this->_has_many[$alias]['foreign_key'], $this->_has_many[$alias]['far_key']);
	$values  = array($this->pk(), $model->pk());

	if ($data !== NULL)
	{
		// Additional data stored in pivot table
		$columns = array_merge($columns, array_keys($data));
		$values  = array_merge($values, array_values($data));
	}

	DB::insert($this->_has_many[$alias]['through'])
		->columns($columns)
		->values($values)
		->execute($this->_db);

	return $this;
}

public as_array( ) (defined in Kohana_ORM)

Returns the values of this object as an array, including any related one-one models that have already been loaded using with()

Return Values

  • array

Source Code

public function as_array()
{
	$object = array();

	foreach ($this->_object as $key => $val)
	{
		// Call __get for any user processing
		$object[$key] = $this->__get($key);
	}

	foreach ($this->_related as $key => $model)
	{
		// Include any related objects that are already loaded
		$object[$key] = $model->as_array();
	}

	return $object;
}

public check( ) (defined in Kohana_ORM)

Validates the current model's data

Return Values

  • boolean

Source Code

public function check()
{
	if ( ! isset($this->_validate))
	{
		// Initialize the validation object
		$this->_validate();
	}
	else
	{
		// Validation object has been created, just exchange the data array
		$this->_validate->exchangeArray($this->_object);
	}

	if ($this->_validate->check())
	{
		// Fields may have been modified by filters
		$this->_object = array_merge($this->_object, $this->_validate->getArrayCopy());

		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

public clear( ) (defined in Kohana_ORM)

Unloads the current object and clears the status.

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function clear()
{
	// Create an array with all the columns set to NULL
	$values = array_combine(array_keys($this->_table_columns), array_fill(0, count($this->_table_columns), NULL));

	// Replace the object and reset the object status
	$this->_object = $this->_changed = $this->_related = array();

	// Replace the current object with an empty one
	$this->_load_values($values);

	$this->reset();

	return $this;
}

public clear_cache( [ string $sql = NULL ] ) (defined in Kohana_ORM)

Proxy method to Database field_data.

Parameters

  • string $sql = NULL - SQL query to clear

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function clear_cache($sql = NULL)
{
	// Proxy to database
	$this->_db->clear_cache($sql);

	ORM::$_column_cache = array();

	return $this;
}

public count_all( ) (defined in Kohana_ORM)

Count the number of records in the table.

Return Values

  • integer

Source Code

public function count_all()
{
	$selects = array();

	foreach ($this->_db_pending as $key => $method)
	{
		if ($method['name'] == 'select')
		{
			// Ignore any selected columns for now
			$selects[] = $method;
			unset($this->_db_pending[$key]);
		}
	}

	$this->_build(Database::SELECT);

	$records = (int) $this->_db_builder->from($this->_table_name)
		->select(array('COUNT("*")', 'records_found'))
		->execute($this->_db)
		->get('records_found');

	// Add back in selected columns
	$this->_db_pending += $selects;

	$this->reset();

	// Return the total number of records in a table
	return $records;
}

public delete( [ mixed $id = NULL ] ) (defined in Kohana_ORM)

Deletes the current object from the database. This does NOT destroy relationships that have been created with other objects.

Parameters

  • mixed $id = NULL - Id to delete

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function delete($id = NULL)
{
	if ($id === NULL)
	{
		// Use the the primary key value
		$id = $this->pk();
	}

	if ( ! empty($id) OR $id === '0')
	{
		// Delete the object
		DB::delete($this->_table_name)
			->where($this->_primary_key, '=', $id)
			->execute($this->_db);
	}

	return $this;
}

public delete_all( ) (defined in Kohana_ORM)

Delete all objects in the associated table. This does NOT destroy relationships that have been created with other objects.

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function delete_all()
{
	$this->_build(Database::DELETE);

	$this->_db_builder->execute($this->_db);

	return $this->clear();
}

public static factory( string $model [, mixed $id = NULL ] ) (defined in Kohana_ORM)

Creates and returns a new model.

Parameters

  • string $model required - Model name
  • mixed $id = NULL - Parameter for find()

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public static function factory($model, $id = NULL)
{
	// Set class name
	$model = 'Model_'.ucfirst($model);

	return new $model($id);
}

public find( [ mixed $id = NULL ] ) (defined in Kohana_ORM)

Finds and loads a single database row into the object.

Parameters

  • mixed $id = NULL - Primary key

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function find($id = NULL)
{
	if ( ! empty($this->_load_with))
	{
		foreach ($this->_load_with as $alias)
		{
			// Bind relationship
			$this->with($alias);
		}
	}

	$this->_build(Database::SELECT);

	if ($id !== NULL)
	{
		// Search for a specific column
		$this->_db_builder->where($this->_table_name.'.'.$this->_primary_key, '=', $id);
	}

	return $this->_load_result(FALSE);
}

public find_all( ) (defined in Kohana_ORM)

Finds multiple database rows and returns an iterator of the rows found.

Tags

  • Chainable -

Return Values

  • Database_Result

Source Code

public function find_all()
{
	if ( ! empty($this->_load_with))
	{
		foreach ($this->_load_with as $alias)
		{
			// Bind relationship
			$this->with($alias);
		}
	}

	$this->_build(Database::SELECT);

	return $this->_load_result(TRUE);
}

public has( string $alias , ORM $model ) (defined in Kohana_ORM)

Tests if this object has a relationship to a different model.

Parameters

  • string $alias required - Alias of the has_many "through" relationship
  • ORM $model required - Related ORM model

Return Values

  • boolean

Source Code

public function has($alias, $model)
{
	// Return count of matches as boolean
	return (bool) DB::select(array('COUNT("*")', 'records_found'))
		->from($this->_has_many[$alias]['through'])
		->where($this->_has_many[$alias]['foreign_key'], '=', $this->pk())
		->where($this->_has_many[$alias]['far_key'], '=', $model->pk())
		->execute($this->_db)
		->get('records_found');
}

public last_query( ) (defined in Kohana_ORM)

Returns last executed query

Return Values

  • string

Source Code

public function last_query()
{
	return $this->_db->last_query;
}

public list_columns( ) (defined in Kohana_ORM)

Proxy method to Database list_columns.

Return Values

  • array

Source Code

public function list_columns()
{
	// Proxy to database
	return $this->_db->list_columns($this->_table_name);
}

public pk( ) (defined in Kohana_ORM)

Returns the value of the primary key

Return Values

  • mixed - Primary key

Source Code

public function pk()
{
	return $this->_object[$this->_primary_key];
}

public reload( ) (defined in Kohana_ORM)

Reloads the current object from the database.

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function reload()
{
	$primary_key = $this->pk();

	// Replace the object and reset the object status
	$this->_object = $this->_changed = $this->_related = array();

	// Only reload the object if we have one to reload
	if ($this->_loaded)
		return $this->find($primary_key);
	else
		return $this->clear();
}

public reload_columns( [ boolean $force = bool FALSE ] ) (defined in Kohana_ORM)

Reload column definitions.

Parameters

  • boolean $force = bool FALSE - Force reloading

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function reload_columns($force = FALSE)
{
	if ($force === TRUE OR empty($this->_table_columns))
	{
		if (isset(ORM::$_column_cache[$this->_object_name]))
		{
			// Use cached column information
			$this->_table_columns = ORM::$_column_cache[$this->_object_name];
		}
		else
		{
			// Grab column information from database
			$this->_table_columns = $this->list_columns(TRUE);

			// Load column cache
			ORM::$_column_cache[$this->_object_name] = $this->_table_columns;
		}
	}

	return $this;
}

public remove( string $alias , ORM $model ) (defined in Kohana_ORM)

Removes a relationship between this model and another.

Parameters

  • string $alias required - Alias of the has_many "through" relationship
  • ORM $model required - Related ORM model

Return Values

  • ORM

Source Code

public function remove($alias, ORM $model)
{
	DB::delete($this->_has_many[$alias]['through'])
		->where($this->_has_many[$alias]['foreign_key'], '=', $this->pk())
		->where($this->_has_many[$alias]['far_key'], '=', $model->pk())
		->execute($this->_db);

	return $this;
}

public reset( [ bool $next = bool TRUE ] ) (defined in Kohana_ORM)

Clears query builder. Passing FALSE is useful to keep the existing query conditions for another query.

Parameters

  • bool $next = bool TRUE - Pass FALSE to avoid resetting on the next call

Source Code

public function reset($next = TRUE)
{
	if ($next AND $this->_db_reset)
	{
		$this->_db_pending   = array();
		$this->_db_applied   = array();
		$this->_db_builder   = NULL;
		$this->_with_applied = array();
	}

	// Reset on the next call?
	$this->_db_reset = $next;

	return $this;
}

public save( ) (defined in Kohana_ORM)

Saves the current object.

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function save()
{
	if (empty($this->_changed))
		return $this;

	$data = array();
	foreach ($this->_changed as $column)
	{
		// Compile changed data
		$data[$column] = $this->_object[$column];
	}

	if ( ! $this->empty_pk() AND ! isset($this->_changed[$this->_primary_key]))
	{
		// Primary key isn't empty and hasn't been changed so do an update

		if (is_array($this->_updated_column))
		{
			// Fill the updated column
			$column = $this->_updated_column['column'];
			$format = $this->_updated_column['format'];

			$data[$column] = $this->_object[$column] = ($format === TRUE) ? time() : date($format);
		}

		$query = DB::update($this->_table_name)
			->set($data)
			->where($this->_primary_key, '=', $this->pk())
			->execute($this->_db);

		// Object has been saved
		$this->_saved = TRUE;
	}
	else
	{
		if (is_array($this->_created_column))
		{
			// Fill the created column
			$column = $this->_created_column['column'];
			$format = $this->_created_column['format'];

			$data[$column] = $this->_object[$column] = ($format === TRUE) ? time() : date($format);
		}

		$result = DB::insert($this->_table_name)
			->columns(array_keys($data))
			->values(array_values($data))
			->execute($this->_db);

		if ($result)
		{
			if ($this->empty_pk())
			{
				// Load the insert id as the primary key
				// $result is array(insert_id, total_rows)
				$this->_object[$this->_primary_key] = $result[0];
			}

			// Object is now loaded and saved
			$this->_loaded = $this->_saved = TRUE;
		}
	}

	if ($this->_saved === TRUE)
	{
		// All changes have been saved
		$this->_changed = array();
	}

	return $this;
}

public save_all( ) (defined in Kohana_ORM)

Updates all existing records

Tags

  • Chainable -

Return Values

  • ORM

Source Code

public function save_all()
{
	$this->_build(Database::UPDATE);

	if (empty($this->_changed))
		return $this;

	$data = array();
	foreach ($this->_changed as $column)
	{
		// Compile changed data omitting ignored columns
		$data[$column] = $this->_object[$column];
	}

	if (is_array($this->_updated_column))
	{
		// Fill the updated column
		$column = $this->_updated_column['column'];
		$format = $this->_updated_column['format'];

		$data[$column] = $this->_object[$column] = ($format === TRUE) ? time() : date($format);
	}

	$this->_db_builder->set($data)->execute($this->_db);

	return $this;
}

public values( array $values ) (defined in Kohana_ORM)

Set values from an array with support for one-one relationships. This method should be used for loading in post data, etc.

Parameters

  • array $values required - Array of key => val

Return Values

  • ORM

Source Code

public function values($values)
{
	foreach ($values as $key => $value)
	{
		if (array_key_exists($key, $this->_object) OR array_key_exists($key, $this->_ignored_columns))
		{
			// Property of this model
			$this->__set($key, $value);
		}
		elseif (isset($this->_belongs_to[$key]) OR isset($this->_has_one[$key]))
		{
			// Value is an array of properties for the related model
			$this->_related[$key] = $value;
		}
	}

	return $this;
}

public with( string $target_path ) (defined in Kohana_ORM)

Binds another one-to-one object to this model. One-to-one objects can be nested using 'object1:object2' syntax

Parameters

  • string $target_path required - Target model to bind to

Return Values

  • void

Source Code

public function with($target_path)
{
	if (isset($this->_with_applied[$target_path]))
	{
		// Don't join anything already joined
		return $this;
	}

	// Split object parts
	$aliases = explode(':', $target_path);
	$target	 = $this;
	foreach ($aliases as $alias)
	{
		// Go down the line of objects to find the given target
		$parent = $target;
		$target = $parent->_related($alias);

		if ( ! $target)
		{
			// Can't find related object
			return $this;
		}
	}

	// Target alias is at the end
	$target_alias = $alias;

	// Pop-off top alias to get the parent path (user:photo:tag becomes user:photo - the parent table prefix)
	array_pop($aliases);
	$parent_path = implode(':', $aliases);

	if (empty($parent_path))
	{
		// Use this table name itself for the parent path
		$parent_path = $this->_table_name;
	}
	else
	{
		if ( ! isset($this->_with_applied[$parent_path]))
		{
			// If the parent path hasn't been joined yet, do it first (otherwise LEFT JOINs fail)
			$this->with($parent_path);
		}
	}

	// Add to with_applied to prevent duplicate joins
	$this->_with_applied[$target_path] = TRUE;

	// Use the keys of the empty object to determine the columns
	foreach (array_keys($target->_object) as $column)
	{
		// Skip over ignored columns
		if( ! in_array($column, $target->_ignored_columns))
		{
			$name   = $target_path.'.'.$column;
			$alias  = $target_path.':'.$column;

			// Add the prefix so that load_result can determine the relationship
			$this->select(array($name, $alias));
		}
	}

	if (isset($parent->_belongs_to[$target_alias]))
	{
		// Parent belongs_to target, use target's primary key and parent's foreign key
		$join_col1 = $target_path.'.'.$target->_primary_key;
		$join_col2 = $parent_path.'.'.$parent->_belongs_to[$target_alias]['foreign_key'];
	}
	else
	{
		// Parent has_one target, use parent's primary key as target's foreign key
		$join_col1 = $parent_path.'.'.$parent->_primary_key;
		$join_col2 = $target_path.'.'.$parent->_has_one[$target_alias]['foreign_key'];
	}

	// Join the related object into the result
	$this->join(array($target->_table_name, $target_path), 'LEFT')->on($join_col1, '=', $join_col2);

	return $this;
}

protected _build( int $type ) (defined in Kohana_ORM)

Initializes the Database Builder to given query type

Parameters

  • int $type required - Type of Database query

Return Values

  • ORM

Source Code

protected function _build($type)
{
	// Construct new builder object based on query type
	switch ($type)
	{
		case Database::SELECT:
			$this->_db_builder = DB::select();
		break;
		case Database::UPDATE:
			$this->_db_builder = DB::update($this->_table_name);
		break;
		case Database::DELETE:
			$this->_db_builder = DB::delete($this->_table_name);
	}

	// Process pending database method calls
	foreach ($this->_db_pending as $method)
	{
		$name = $method['name'];
		$args = $method['args'];

		$this->_db_applied[$name] = $name;

		call_user_func_array(array($this->_db_builder, $name), $args);
	}

	return $this;
}

protected _initialize( ) (defined in Kohana_ORM)

Prepares the model database connection, determines the table name, and loads column information.

Return Values

  • void

Source Code

protected function _initialize()
{
	if ( ! is_object($this->_db))
	{
		// Get database instance
		$this->_db = Database::instance($this->_db);
	}

	if (empty($this->_table_name))
	{
		// Table name is the same as the object name
		$this->_table_name = $this->_object_name;

		if ($this->_table_names_plural === TRUE)
		{
			// Make the table name plural
			$this->_table_name = Inflector::plural($this->_table_name);
		}
	}

	if ( ! empty($this->_ignored_columns))
	{
		// Optimize for performance
		$this->_ignored_columns = array_combine($this->_ignored_columns, $this->_ignored_columns);
	}

	foreach ($this->_belongs_to as $alias => $details)
	{
		$defaults['model']       = $alias;
		$defaults['foreign_key'] = $alias.$this->_foreign_key_suffix;

		$this->_belongs_to[$alias] = array_merge($defaults, $details);
	}

	foreach ($this->_has_one as $alias => $details)
	{
		$defaults['model']       = $alias;
		$defaults['foreign_key'] = $this->_object_name.$this->_foreign_key_suffix;

		$this->_has_one[$alias] = array_merge($defaults, $details);
	}

	foreach ($this->_has_many as $alias => $details)
	{
		$defaults['model']       = Inflector::singular($alias);
		$defaults['foreign_key'] = $this->_object_name.$this->_foreign_key_suffix;
		$defaults['through']     = NULL;
		$defaults['far_key']     = Inflector::singular($alias).$this->_foreign_key_suffix;

		$this->_has_many[$alias] = array_merge($defaults, $details);
	}

	// Load column information
	$this->reload_columns();
}

protected _load( ) (defined in Kohana_ORM)

Loads the given model

Return Values

  • ORM

Source Code

protected function _load()
{
	if ( ! $this->_loaded AND ! $this->empty_pk() AND ! isset($this->_changed[$this->_primary_key]))
	{
		// Only load if it hasn't been loaded, and a primary key is specified and hasn't been modified
		return $this->find($this->pk());
	}
}

protected _load_result( [ boolean $multiple = bool FALSE ] ) (defined in Kohana_ORM)

Loads a database result, either as a new object for this model, or as an iterator for multiple rows.

Parameters

  • boolean $multiple = bool FALSE - Return an iterator or load a single row

Tags

  • Chainable -

Return Values

  • ORM - For single rows
  • ORM_Iterator - For multiple rows

Source Code

protected function _load_result($multiple = FALSE)
{
	$this->_db_builder->from($this->_table_name);

	if ($multiple === FALSE)
	{
		// Only fetch 1 record
		$this->_db_builder->limit(1);
	}

	// Select all columns by default
	$this->_db_builder->select($this->_table_name.'.*');

	if ( ! isset($this->_db_applied['order_by']) AND ! empty($this->_sorting))
	{
		foreach ($this->_sorting as $column => $direction)
		{
			if (strpos($column, '.') === FALSE)
			{
				// Sorting column for use in JOINs
				$column = $this->_table_name.'.'.$column;
			}

			$this->_db_builder->order_by($column, $direction);
		}
	}

	if ($multiple === TRUE)
	{
		// Return database iterator casting to this object type
		$result = $this->_db_builder->as_object(get_class($this))->execute($this->_db);

		$this->reset();

		return $result;
	}
	else
	{
		// Load the result as an associative array
		$result = $this->_db_builder->as_assoc()->execute($this->_db);

		$this->reset();

		if ($result->count() === 1)
		{
			// Load object values
			$this->_load_values($result->current());
		}
		else
		{
			// Clear the object, nothing was found
			$this->clear();
		}

		return $this;
	}
}

protected _load_values( array $values ) (defined in Kohana_ORM)

Loads an array of values into into the current object.

Parameters

  • array $values required - Values to load

Tags

  • Chainable -

Return Values

  • ORM

Source Code

protected function _load_values(array $values)
{
	if (array_key_exists($this->_primary_key, $values))
	{
		// Set the loaded and saved object status based on the primary key
		$this->_loaded = $this->_saved = ($values[$this->_primary_key] !== NULL);
	}

	// Related objects
	$related = array();

	foreach ($values as $column => $value)
	{
		if (strpos($column, ':') === FALSE)
		{
			if ( ! isset($this->_changed[$column]))
			{
				$this->_object[$column] = $value;
			}
		}
		else
		{
			list ($prefix, $column) = explode(':', $column, 2);

			$related[$prefix][$column] = $value;
		}
	}

	if ( ! empty($related))
	{
		foreach ($related as $object => $values)
		{
			// Load the related objects with the values in the result
			$this->_related($object)->_load_values($values);
		}
	}

	return $this;
}

Returns an ORM model for the given one-one related alias

Parameters

  • string $alias required - Alias name

Return Values

  • ORM

Source Code

protected function _related($alias)
{
	if (isset($this->_related[$alias]))
	{
		return $this->_related[$alias];
	}
	elseif (isset($this->_has_one[$alias]))
	{
		return $this->_related[$alias] = ORM::factory($this->_has_one[$alias]['model']);
	}
	elseif (isset($this->_belongs_to[$alias]))
	{
		return $this->_related[$alias] = ORM::factory($this->_belongs_to[$alias]['model']);
	}
	else
	{
		return FALSE;
	}
}

protected _validate( ) (defined in Kohana_ORM)

Initializes validation rules, callbacks, filters, and labels

Return Values

  • void

Source Code

protected function _validate()
{
	$this->_validate = Validate::factory($this->_object);

	foreach ($this->_rules as $field => $rules)
	{
		// PHP converts TRUE to int 1, so we have to fix that
		$field = ($field === 1) ? TRUE : $field;

		$this->_validate->rules($field, $rules);
	}

	foreach ($this->_filters as $field => $filters)
	{
		// PHP converts TRUE to int 1, so we have to fix that
		$field = ($field === 1) ? TRUE : $field;

		$this->_validate->filters($field, $filters);
	}

	// Use column names by default for labels
	$columns = array_keys($this->_table_columns);

	// Merge user-defined labels
	$labels = array_merge(array_combine($columns, $columns), $this->_labels);

	foreach ($labels as $field => $label)
	{
		$this->_validate->label($field, $label);
	}

	foreach ($this->_callbacks as $field => $callbacks)
	{
		// PHP converts TRUE to int 1, so we have to fix that
		$field = ($field === 1) ? TRUE : $field;
		
		foreach ($callbacks as $callback)
		{
			if (is_string($callback) AND method_exists($this, $callback))
			{
				// Callback method exists in current ORM model
				$this->_validate->callback($field, array($this, $callback));
			}
			else
			{
				// Try global function
				$this->_validate->callback($field, $callback);
			}
		}
	}
}

protected empty_pk( ) (defined in Kohana_ORM)

Returns whether or not primary key is empty

Return Values

  • bool

Source Code

protected function empty_pk()
{
	return (empty($this->_object[$this->_primary_key]) OR $this->_object[$this->_primary_key] === '0');
}