您可能需要这样的 HABTM 设置:
Class Tag extends AppModel {
public $name = 'Tag';
public $hasAndBelongsToMany = array(
'Article' => array(
'className' => 'Article',
'joinTable' => 'articles_tags',
'foreignKey' => 'tag_id',
'associationForeignKey' => 'article_id',
)
);
}
Class ArticlesTag extends AppModel {
public $name = 'ArticlesTag';
}
Class Article extends AppModel {
public $name = 'Article';
public $hasAndBelongsToMany = array(
'Tag' => array(
'className' => 'Tag',
'joinTable' => 'articles_tags',
'foreignKey' => 'article_id',
'associationForeignKey' => 'tag_id',
)
);
}
在您的 AppModel 中添加以下内容,您将永远不会回头:
class AppModel extends Model {
public $actsAs = array('Containable');
}
在控制器中:
$results = $this->Tag->find('all, array(
'contain' => array('Article)
));
$this->set('results', $results);
在视图中:
<ul class="tags">
<?php foreach ($results as $data) : ?>
<li class="tag"><?php
echo $this->Html->link($data['Tag']['name'] . ' (' . count($data['Article']) . ')',
'/tag/' . $data['Tag']['slug'],
array('title' => 'View articles for ' . $data['Tag']['name'], 'escape' => false));
?></li>
<?php endforeach; ?>
</ul>
希望这会有所帮助。