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

Has One - 關聯 - Orm 套件

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

Orm 是 物件关联对映(Object Relational Mapper) 的简写,它做两件事:
对应你资料库里的资料列到物件, 并能让你在这些物件之间建立关係。
它紧随 活动记录模式( Active Record Pattern),但也受到其他系统的影响。

关联:Has One

Specifies a one-to-one 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_User and it has one a Model_Profile (which in turn belongs to the user). The ID of the Model_User is saved with the Model_Profile instance in its own table. This means the profiles table will have a column user_id (or something else you configure), while the user table won't mention the profile. If you keep to the defaults all you need to do is add 'profile' to the $_has_one static property of the Model_User:

protected static $_has_one = array('profile');

Below are examples for establishing and breaking has-one relations:

// 主要及关联物件两者都是新的:
$user = new Model_User();
$user->profile = new Model_Profile();
$user->save();

// both main and related object already exist
$user = Model_User::find(6);
$user->profile = Model_Profile::find(1);
$user->save();

// break the relationship established above
$user = Model_User::find(6);
$user->profile = null;
$user->save();

Full config example with defaults as values

// 在有一个 profile 的 Model_User 中
protected static $_has_one = array(
	'profile' => array(
		'key_from' => 'id',
		'model_to' => 'Model_Profile',
		'key_to' => 'user_id',
		'cascade_save' => true,
		'cascade_delete' => false,
	)
);