0

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?

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488

1 Answers1

1

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 = ...;
kero
  • 10,647
  • 5
  • 41
  • 51
  • Thanks, kingkero! So what you're saying is that for the relationships of `has_one` and `has_many` I have to use the model that is defined as `belongs_to` and can't create related model from the model that has relationship `has_one`\`has_many`? What about this solution that you mentioned `$text->compiledData = $compiledData; $text->save();`? instead of `$compiledText->text = ORM::factory('Text', $specificId)` ? – Max Koretskyi Feb 18 '15 at 07:31
  • 1
    @Maximus Yes, it looks this way. I thought for a `has_one` it could be set in that model but it doesn't look this way (maybe possible to unset, but not so easily to set if it hasn't been yet). Seems like you need to do `$compiledText->text = $text; $compiledText->save(); $text->reload();` – kero Feb 18 '15 at 12:17