Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kohana 3 ORM: constructor "after load"

Tags:

php

orm

kohana

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.

like image 677
Tesserex Avatar asked Jan 28 '26 13:01

Tesserex


1 Answers

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;
}
like image 157
biakaveron Avatar answered Jan 30 '26 02:01

biakaveron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!