我在books表和authors表之间有一个HABTM关系,并与authors_books表连接。 但是,我找不到在我的视图中显示字段firstname,lastname和fullname的解决方案。
书模型:
class Book extends AppModel {
var $name = 'Book';
var $hasAndBelongsToMany = array(
'Author' => array(
'className' => 'Author',
'joinTable' => 'authors_books',
'foreignkey' => 'book_id',
'associatioanForeignKey' => 'author_id'
)
);
作者模型:
class Author extends AppModel {
var $name = 'Author';
var $virtualFields = array(
'fullname' => "CONCAT(firstname,' ',lastname)"
);
var $fullname = 'fullname';
var $hasAndBelongsToMany = array(
'Book' => array(
'className' => 'Book',
'joinTable' => 'authors_books',
'foreignkey' => 'author_id',
'associatioanForeignKey' => 'book_id'
)
);
books_controller:
function view($id) {
$this->Book->id = $id;
$this->set('book', $this->Book->read());
}
我的wiev.ctp中的debug($ book)给出了以下结果:
Array
(
[Book] => Array
(
[id] => 8
[title] => A Forest of Kings: The Untold Story of the Ancient Maya
)
[Author] => Array
(
[0] => Array
(
[id] => 6
[firstname] => Linda
[lastname] => Schele
[fullname] => Linda Schele
)
[1] => Array
(
[id] => 7
[firstname] => David
[lastname] => Freidel
[fullname] => David Freidel
)
)
)
我相信数组中的[0] [1]索引是问题所在。 我已经搜索了这个问题,发现了一些关于这个问题的文章,但是无法让任何解决方案起作用。
非常感谢任何帮助。我正在使用cakephp 1.3.3
由于
答案 0 :(得分:3)
您通常会遍历Author数组,因为您可以拥有不同数量的作者。
<ul>
<?php foreach($book['Author'] as $author){ ?>
<li><?php print($author['fullname']); ?></li>
<?php } ?>
</ul>