我有一个2个CakePHP模型,文章和类别,使用hasAndBelongsToMany关系附加,如下所示:
$category = new Category();
$category->bindModel(array('hasAndBelongsToMany' => array(
'Article' => array(
'className' => 'Article',
'joinTable' => 'articles_categories',
'foreignKey' => 'category_id',
'associationForeignKey' => 'article_id',
'fields' => 'id,name'
))));
$this->set('categories', $category->find('all',
array(
'fields' => 'id,name'
)));
...但是,当我打印出$ categories时,我得到以下内容:
Array
(
[0] => Array
(
[Category] => Array
(
[id] => 31
[name] => category name
[article_count] => 1
)
[Article] => Array
(
[0] => Array
(
[id] => 1445
[name] => article name
[teaser] =>
[author_id] => 3
[ArticlesCategory] => Array
(
[id] => 6634
[article_id] => 1445
[category_id] => 31
[author_id] => 3
[created] => 2014-03-10 12:27:26
[modified] => 2014-03-10 12:27:26
)
)
)
)
我真的不需要[Article]的[ArticlesCategory]成员。这只是让我回到我已有的信息。我尝试过限制递归,但这没有用。
我怎么能摆脱这个?
答案 0 :(得分:0)
您有两种选择:
[1]将递归值减少到0(CakePHP默认值:1)
$category->recursive = 0;
$category->find('all',
array(
'fields' => 'id,name'
))
[2]开始使用ContainableBehaviour(我自己的偏好),它可以让您更好地控制检索到的模型数据
将以下内容添加到AppModel以进行应用范围覆盖:
public $actsAs = array('Containable');
find方法变为:
$category->find('all',
array(
'fields' => 'id, name',
'contain' => 'Article'
))
应该这样做!