开发者

Kohana 3 ORM: constructor "after load"

开发者 https://www.devze.com 2023-01-14 23:58 出处:网络
Is there any way in Kohana 3\'s ORM to run a chunk of code in a model开发者_高级运维, but only after that model has been loaded from the database? A simple example is a required has_one relationship.

Is there any way in Kohana 3's ORM to run a chunk of code in a model开发者_高级运维, but only after that model has been loaded from the database? A simple example is a required has_one relationship.

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

Now what if all users have to have some other property, so if Bob doesn't exist, it will have to be created? Right now, in the place where this line is running, I'm checking for null primary key, and instructing the model to add that relationship if so. But is there any way to have it done by the model? The problem with the constructor is that models can be constructed empty just before being populated from the DB, as is visible in this example, so I don't want that.


Just create model method with all logic required:

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


Try overloading the find() method 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;
    }

}
0

精彩评论

暂无评论...
验证码 换一张
取 消