2010-09-08 60 views
0

我在書籍表和作者表之間建立了一個HABTM關係,並加入了authors_books表。 但是,我找不到在我的視圖中顯示字段firstname,lastname和fullname的解決方案。如何在視圖中顯示HABTM關係的結果?

書型號:

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給這些結果:

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

你究竟試過了什麼?這不應該是一個問題。也許你混淆了數組的語法? – geon 2010-09-08 13:13:52

回答

3

你通常會環比作者陣列,因爲你可以有不同數量的作者。

<ul> 
    <?php foreach($book['Author'] as $author){ ?> 
     <li><?php print($author['fullname']); ?></li> 
    <?php } ?> 
</ul> 
+0

這工作完美。非常感謝! – Lars 2010-09-09 07:26:04