CakePHP1.2 hasOne, belongsTo, hasMany, hasAndBelongsToManyの理解2
つづき。
$hasMany
http://book.cakephp.org/ja/view/82/hasMany
例)
1ユーザに対して複数のコメントが存在する。
<?php class User extends AppModel { var $name = 'User'; var $hasMany = array( 'Comment' => array( 'className' => 'Comment', 'foreignKey' => 'user_id', 'conditions' => array('Comment.status' => '1'), 'order' => 'Comment.created DESC', 'limit' => '5', 'dependent'=> true ) ); } ?>
結果
(
[User] => Array
(
[id] => 121
[name] => Gwoo the Kungwoo
[created] => 2007-05-01 10:31:01
)
[Comment] => Array
(
[0] => Array
(
[id] => 123
[user_id] => 121
[title] => On Gwoo the Kungwoo
[body] => The Kungwooness is not so Gwooish
[created] => 2006-05-01 10:31:01
)
[1] => Array
(
[id] => 123
[user_id] => 121
[title] => More on Gwoo
[body] => But what of the ‘Nut? [created] => 2006-05-01 10:41:01
)
)
)
hasAndBelongsToMany (HABTM)
http://book.cakephp.org/ja/view/83/hasAndBelongsToMany-HABTM
3つのテーブルを結びつける
<?php class Recipe extends AppModel { var $name = 'Recipe'; var $hasAndBelongsToMany = array( 'Tag' => array( 'className' => 'Tag', 'joinTable' => 'recipes_tags', 'with' => '', 'foreignKey' => 'recipe_id', 'associationForeignKey' => 'tag_id', 'unique' => true, 'conditions' => '', 'fields' => '', 'order' => '', 'limit' => '', 'offset' => '', 'finderQuery' => '', 'deleteQuery' => '', 'insertQuery' => '' ) ); } ?>
結果
(
[Recipe] => Array
(
[id] => 2745
[name] => Chocolate Frosted Sugar Bombs
[created] => 2007-05-01 10:31:01
[user_id] => 2346
)
[Tag] => Array
(
[0] => Array
(
[id] => 123
[name] => Breakfast
)
[1] => Array
(
[id] => 124
[name] => Dessert
)
[2] => Array
(
[id] => 125
[name] => Heart Disease
)
)
)