CakePHP1.2 hasOne, belongsTo, hasMany, hasAndBelongsToManyの理解1

CakePHPのmodelが便利すぎる。


$hasOne

http://book.cakephp.org/ja/view/80/hasOne

1対1の関係。
例)
ユーザーは一つのプロフィールを持っている。

<?php

class User extends AppModel {
    var $name = 'User';          
    var $hasOne = array(
        'Profile' => array(
            'className'    => 'Profile',
            'conditions'   => array('Profile.published' => '1'),
            'dependent'    => true
        )
    );    
}
?>

結果

(
[User] => Array
(
[id] => 121
[name] => Gwoo the Kungwoo
[created] => 2007-05-01 10:31:01
)
[Profile] => Array
(
[id] => 12
[user_id] => 121
[skill] => Baking Cakes
[created] => 2007-05-01 10:31:01
)
)

$belongsTo

http://book.cakephp.org/ja/view/81/belongsTo
$hasOneの逆アクセス。ProfileからUserをひっぱる。

<?php

class Profile extends AppModel {
    var $name = 'Profile';                
    var $belongsTo = array(
        'User' => array(
            'className'    => 'User',
            'foreignKey'    => 'user_id'
        )
    );  
}
?>

結果

Array
(
[Profile] => Array
(
[id] => 12
[user_id] => 121
[skill] => Baking Cakes
[created] => 2007-05-01 10:31:01
)
[User] => Array
(
[id] => 121
[name] => Gwoo the Kungwoo
[created] => 2007-05-01 10:31:01
)
)