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,
)
);