public function load(Database_Query_Builder_Select $query = NULL, $limit = 1)
{
// Load changed values as search parameters
$changed = $this->changed();
if (!$query and $limit == 1 and !count($changed)) {
return $this;
} elseif (!$query) {
$query = DB::select();
}
$query->from($this->_table);
$table = is_array($this->_table) ? $this->_table[1] : $this->_table;
foreach ($this->_fields as $name => $field) {
if (!$field->in_db) {
// Multiple relations cannot be loaded this way
continue;
}
$query->select(array($field->_database_unwrap("{$table}.{$field->column}"), $name));
if (array_key_exists($name, $changed)) {
$query->where("{$table}.{$field->column}", '=', $field->_database_wrap($changed[$name]));
}
}
if ($limit) {
$query->limit($limit);
}
if ($this->_sorting) {
foreach ($this->_sorting as $field => $direction) {
$query->order_by($field, $direction);
}
}
if ($limit === 1) {
$result = $query->execute($this->_db);
if (count($result)) {
$this->_changed = array();
$this->state('loading')->values($result[0])->state('loaded');
}
return $this;
} else {
return $query->as_object(get_class($this))->execute($this->_db);
}
}