codeigniter-base-model
codeigniter-base-model copied to clipboard
Does `as_object()` can return model instead of just object?
CI 2.x support getting result as model if we pass the model class name when getting one or many result.
After I read the source of MY_Model
, I think it is not supported.
Currently
$this->user_model->as_object()->get(1)
return object.
What I desire is
$this->user_model->as_object('user_model')->get(1)
return instance of user_model class or may be
$this->user_model->as_model()->get(1)
or
$this->user_model->get(1)
returns user_model not object
How can I achieved that?
P.S. Also with with('friends')
, currently friends are simple object.
I've achieved this by overriding the get() function within the model.
public function get($primary_value) { $row = parent::get($primary_value); foreach($row as $k => $v) { $this->{$k} = $v; } return $row ? $this : null; }
Resolved. https://github.com/jamierumbelow/codeigniter-base-model/issues/61
I'm just adding here a little remark: be careful if you try to use this little code snippet inside an observer like what I used on the event 'after_Get', because if you use one of the get_many...() functions all the rows returned by that function will be overwritten by the last row returned from the result set! I solved this problem by adding a clone before this:
function to_row($obj) {
foreach ($obj as $k => $v) {
$this->{$k} = $v;
}
return clone $this;
}