関連モデル hasManyとbelongsToの違い
「特定のuserが一定期間中に作成したnotes一覧」の取得を、
- Noteモデルから取得(belongsTo設定使用)
と
- Userモデルから取得(hasMany設定)
で行って比べてみました。
Noteモデルから取得(belongsTo設定使用)
アクションの記載は以下の通り。
$this->Note->recursive = 0; $notes_for_user = $this->Note->find('all', array( 'conditions' => array( 'Note.user_id' => $user_id, 'Note.created >= ' => date('Y-m-d H:i:s', $this_timestamp), ), 'order' => array( 'Note.created' => 'asc', ), ));
結果は以下の通り。
$data = array( '0'=> array( ['User'] => array([指定ユーザデータ]), ['Note'] => array([notesデータ一覧]), ), );
発行SQL
SELECT `Note`.`id`, `Note`.`user_id`, `Note`.`title`, `Note`.`detail`, `Note`.`created`, `User`.`id`, `User`.`name` FROM `notes` AS `Note` LEFT JOIN `users` AS `User` ON (`Note`.`user_id` = `User`.`id`) WHERE `Note`.`user_id` = 1 AND `Note`.`created` >= '2010-01-01 00:00:00' ORDER BY `Note`.`created` asc
Userモデルから取得(hasMany設定使用)
アクションの記載は以下の通り。
notes作成期間絞り込みのため、ここでhasManyの設定を追加しています。
$this->User->recursive = 1; $this->User->hasMany['Note']['conditions'] = array( 'Note.created >= ' => date('Y-m-d H:i:s', $this_timestamp), ); $notes_for_user = $this->User->find('all', array( 'conditions' => array( 'User.id' => $id, 'fields' => array('User.name'), ), ));
結果
$data = array( '0'=> array( ['Note'] => array([note1件分のデータ]), ['User'] => array([指定ユーザのデータ]), ), ・・・・・(以下、取得Note件数分繰り返し) );
SQLは、2つ発行されています。
SELECT `User`.`id`, `User`.`name` FROM `users` AS `User` WHERE `User`.`id` = 1
SELECT `Note`.`id`, `Note`.`user_id`, `Note`.`title`, `Note`.`detail`, `Note`.`created` FROM `notes` AS `Note` WHERE `Note`.`created` >= '2010-01-01 00:00:00' AND `Note`.`user_id` = (1) ORDER BY `Note`.`created` asc
結果
「特定のuserが一定期間中に作成したnotes一覧」
Noteモデルから取得したデータの方が、無駄がないし出力もし易いという結果になりました。
user/indexにポータル的な機能を持たせて、新着のnotesを表示しようと思っていたので、「Userモデルから取得できないかな?」と思ってこんな検討をしたのですが、Noteモデルからとるべし、な結果になりました。
データの主眼(?)はNoteという事なのでしょうか。
このあたりの判断は、まだ慣れが足りません・・・