私はhttp://book.cakephp.org/view/83/hasAndBelongsToMany-HABTMで文書化された例に従っています
hasOneを使用して関連データを取得しようとしています。
3つのテーブルposts、tags、posts_tagsを作成しました。投稿をデバッグするために次のコードを記述しました。
$this->Post->bindModel(array(
'hasOne' => array(
'PostsTag',
'FilterTag' => array(
'className' => 'Tag',
'foreignKey' => false,
'conditions' => array('FilterTag.id = PostsTag.tag_id')
))));
$output=$this->Post->find('all', array(
'fields' => array('Post.*')
));
debug($output);
以下のような出力を期待していました。
Array
(
0 => Array
{
[Post] => Array
(
[id] => 1
[title] => test post 1
)
[Tag] => Array
(
[0] => Array
(
[id] => 1
[name] => php
)
[1] => Array
(
[id] => 2
[name] => javascript
)
[2] => Array
(
[id] => 3
[name] => xml
)
)
}
しかし、私の出力にはタグがまったくありません。これが私が得たものです。
Array
(
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => test post1
)
)
[1] => Array
(
[Post] => Array
(
[id] => 2
[title] => test post2
)
)
)
投稿と一緒に関連付けられたタグを取得するにはどうすればよいですか。
私は何かが欠けていることを知っていますが、理解することができません。どんな助けでも大歓迎です。
編集1:
わかりました、私はさらにいくつかの亜種を試しました。
私は試した:
$this->Post->bindModel(array(
'hasOne' => array(
'PostsTag',
'FilterTag' => array(
'className' => 'Tag',
'foreignKey' => false,
'conditions' => array('FilterTag.id = PostsTag.tag_id')
))));
$output=$this->Post->find('all');
私が得た:
Array
(
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => test post1
)
[PostsTag] => Array
(
[id] => 1
[post_id] => 1
[tag_id] => 1
)
[FilterTag] => Array
(
[id] => 1
[name] => php
)
)
[1] => Array
(
[Post] => Array
(
[id] => 1
[title] => test post1
)
[PostsTag] => Array
(
[id] => 2
[post_id] => 1
[tag_id] => 2
)
[FilterTag] => Array
(
[id] => 2
[name] => javascript
)
)
[2] => Array
(
[Post] => Array
(
[id] => 1
[title] => test post1
)
[PostsTag] => Array
(
[id] => 3
[post_id] => 1
[tag_id] => 3
)
[FilterTag] => Array
(
[id] => 3
[name] => xml
)
)
)
私は試した:
$output=$this->Post->find('all', array(
'fields' => array('Post.*', 'FilterTag.*'),
'recursive' => 1
));
私が得た:
Array
(
[0] => Array
(
[Post] => Array
(
[id] => 1
[title] => test post1
)
[FilterTag] => Array
(
[id] => 1
[name] => php
)
)
[1] => Array
(
[Post] => Array
(
[id] => 1
[title] => test post1
)
[FilterTag] => Array
(
[id] => 2
[name] => javascript
)
)
[2] => Array
(
[Post] => Array
(
[id] => 1
[title] => test post1
)
[FilterTag] => Array
(
[id] => 3
[name] => xml
)
)
)
何かが足りない場合に備えて、Postsコントローラーは次のとおりです。
class PostsController extends AppController {
var $name = 'Posts';
var $helpers = array('Html','Ajax','Javascript');
var $components = array( 'RequestHandler' );
function index() {
$this->Post->bindModel(array(
'hasOne' => array(
'PostsTag',
'FilterTag' => array(
'className' => 'Tag',
'foreignKey' => false,
'conditions' => array('FilterTag.id = PostsTag.tag_id')
))));
$output=$this->Post->find('all', array(
'fields' => array('Post.*', 'FilterTag.*'),
'recursive' => 1
));
}
}
そして、これが私の投稿モデルです。
class Post extends AppModel {
var $name = 'Post';
}
クックブックの例が機能しないのはなぜだろうか。