我正在关注http://book.cakephp.org/view/83/hasAndBelongsToMany-HABTM中记录的示例
我正在尝试使用 hasOne 检索相关数据。
我创建了 3 个表帖子、标签和帖子标签。我编写了以下代码来调试帖子。
$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';
}
我仍然想知道为什么食谱中的示例不起作用。