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