当前位置: 首页 > 文档资料 > FuelPHP 中文文档 >

Belongs To - 關聯 - Orm 套件

优质
小牛编辑
131浏览
2023-12-01

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