codeigniter-base-model icon indicating copy to clipboard operation
codeigniter-base-model copied to clipboard

Does `as_object()` can return model instead of just object?

Open twnaing opened this issue 11 years ago • 3 comments

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.

twnaing avatar Jan 09 '13 08:01 twnaing

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;
}

steadweb avatar Jan 20 '13 17:01 steadweb

Resolved. https://github.com/jamierumbelow/codeigniter-base-model/issues/61

steadweb avatar Feb 01 '13 08:02 steadweb

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;
}

digfish avatar Feb 06 '13 14:02 digfish