kohana ORM-为has_many,has_one关系添加新记录



Kohana ORM在模型之间具有以下关系:

  1. has_one
  2. has_many
  3. has_many_through

例如,我定义了以下内容:

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

我需要为每个关系创建一个新的相关模型。我只在ORM类中找到了add方法,该方法允许添加通过has_many_through关系链接的相关模型,如下所示:

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

但我在任何地方都找不到如何为has_one和简单的has_many关系添加相关模型。有可能吗?

问题的关键是每个has_manyhas_one的"另一侧"都是一个belongs_to。这就是保存信息的模型。

在您的案例中,Model_CompiledText具有列idText(使用特定别名)。要(取消)设置关系,您需要操作此字段。假设你有一个名为textbelongs_to,你会这样做:

$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();

has_one的情况下,您可以直接通过父级访问它,也是如此

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

最新更新