Kohana ORM在模型之间具有以下关系:
- has_one
- has_many
- 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_many
和has_one
的"另一侧"都是一个belongs_to
。这就是保存信息的模型。
在您的案例中,Model_CompiledText
具有列idText
(使用特定别名)。要(取消)设置关系,您需要操作此字段。假设你有一个名为text
的belongs_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 = ...;