Has Many - 關聯 - Orm 套件
Orm 是 物件关联对映(Object Relational Mapper) 的简写,它做两件事:
对应你资料库里的资料列到物件, 并能让你在这些物件之间建立关係。
它紧随 活动记录模式( Active Record Pattern),但也受到其他系统的影响。
关联:Has Many
Specifies a one-to-many relationship to another model. The target model must include a "Belongs To" reference to the current model to allow the inverse relationship.
範例
Let's say we have a model Model_Post and it has many Model_Comments (which in turn belong to the post). The ID of the Model_Post is saved with the Model_Comment instance in its own table. This means the comments table will have a column post_id (or something else you configure), while the posts table won't mention the comments. If you keep to the defaults all you need to do is add 'comments' to the $_has_many static property of the Model_User:
protected static $_has_many = array('comments');
Below are examples for establishing and breaking has-many relations:
// 主要及关联物件两者都是新的:
$post = new Model_Post();
$post->comments[] = new Model_Comment();
$post->save();
// both main and related object already exist
$post = Model_Post::find(1);
$post->comments[6] = Model_Comment::find(6); // assigning it to comments[6] is not required but recommended
$post->save();
// break the relationship established above
$post = Model_Post::find(1);
unset($post->comments[6]);
$post->save();
Full config example with defaults as values
// 在有多个 comments 的 Model_Post 中
protected static $_has_many = array(
'comments' => array(
'key_from' => 'id',
'model_to' => 'Model_Comment',
'key_to' => 'post_id',
'cascade_save' => true,
'cascade_delete' => false,
)
);