Kohana 3 ORM: post-load constructor

Is there any way in Kohana 3 ORM to run a piece of code in a model, but only after this model has been loaded from the database? A simple example is the required has_one relation.

   ORM::factory('user')->where('name', '=', 'Bob')->find();

Now, if all users should have some other property, so if Bob doesn't exist, will he need to be created? Right now, where this line works, I check the zero primary key and instruct the model to add this connection, if so. But is there a way to do this with a model? The problem with the constructor is that the models can be constructed empty just before filling out the database, as this example shows, so I don't want this.

+3
source share
2 answers

Just create a model method with all the necessary logic:

public function get_user($username)
{
    $this->where('name', '=', $username)->find();
    if ( ! $this->_loaded)
    {
        // user not found
    }
    else
    {
        // user exists, do something else
    }
    // make it chainable to use something like this:
    //   echo ORM::factory('user')->get_user('Bob')->username;
    return $this;
}
+3
source

Try overloading the method find()in your model:

class Model_User extends ORM {

    public function find($id = NULL) {
        $result = parent::find($id);
        if (!$result->loaded()) {
            // not found so do something
        }
        return $result;
    }

}
+3
source

Source: https://habr.com/ru/post/1762759/


All Articles