ormkohanakohana-ormkohana-3.3

kohana ORM - add new record for has_many, has_one relationships


Kohana ORM has the following relationships between model:

  1. has_one
  2. has_many
  3. has_many_through

For example, I have the following defined:

class Model_ORM_Text extends ORM {

    protected $_has_one = array(
        'compiledData' => array('model' => 'CompiledText', 'foreign_key' => 'idText'),
    );

    protected $_has_many = array(
        'translations' => array('model' => 'TextTranslation', 'foreign_key' => 'idText')
    );

    protected $_has_many_through = array(
        'tags' => array('model' => 'TextTranslation', 'through' => 'rl_text_tags')
    );
}

I need to create a new related model for each of these relationships. I've only found the add method in ORM class that allows adding related model that is linked through has_many_through relationships, like this:

$text->add("tags", $tagId);

But I can't find anywhere how I can add a related model for the has_one and simple has_many relationships. Is it possible?


Solution

  • The key to the question is that on the "other" side of every has_many and has_one is a belongs_to. And this is the model where the information is saved.

    In your case Model_CompiledText has the column idText (under a specific alias). To (un)set the relationship, you need to manipulate this field. Say you have a belongs_to in there under the name text, this is how you would do it:

    $compiledText = ORM::factory('CompiledText');
    
    // set text
    // Version 1
    $compiledText->text = ORM::factory('Text', $specificId);
    // Version 2
    $compiledText->text = ORM::factory('Text')->where('specificColumn', '=', 'specificValue')
        ->find();
    
    // unset text
    $compiledText->text = null
    
    // save
    $compiledText->save();
    

    In the case of a has_one you can access it directly via the parent and so do

    $text->compiledData->text = ...;