Orm

Orm 是 物件關聯對映(Object Relational Mapper) 的简寫,它做兩件事:
對應你資料庫裡的資料列到物件, 并能让你在这些物件之間建立關係。
它緊隨 活动記錄模式( Active Record Pattern),但也受到其他系统的影響。

關聯:Belongs To

在其資料表中有關聯的主鍵,屬於一个關聯物件。屬於一个關聯的物件。 这是 HasOneHasMany 關聯的另一面。

範例

Let's say we have a model Model_Comment and it belongs to a Model_Post (which in turn has many comments) 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). If you keep to the defaults all you need to do is add 'post' to the $_belongs_to static property of the Model_Comment:

protected static $_belongs_to = array('post');

Below are examples for establishing and breaking belongs-to relations:

// 主要及關聯物件兩者都是新的:
$comment = new Model_Comment();
$comment->post = new Model_Post();
$comment->save();

// both main and related object already exist
$comment = Model_Comment::find(6);
$comment->post = Model_Post::find(1);
$comment->save();

// break the relationship established above
$comment = Model_Comment::find(6);
$comment->post = null;
$comment->save();

Full config example with defaults as values

// 在屬於 post 的 Model_Comment 中
protected static $_belongs_to = array(
	'post' => array(
		'key_from' => 'post_id',
		'model_to' => 'Model_Post',
		'key_to' => 'id',
		'cascade_save' => true,
		'cascade_delete' => false,
	)
);