开发者

How to display results from a HABTM relationship in a view?

I have a HABTM relationship between a books table and an authors table, joined with an authors_books table. However, I can't find a solution to display the fields firstname, lastname and fullname in my view.

book-model:

class Book extends AppModel {
var $name = 'Book';
var $hasAndBelongsToMany = array(
    'Author' => array(
        'className' => 'Author',
        'joinTable' => 'authors_books',
        'foreignkey' => 'book_id',
        'associatioanForeignKey' => 'author_id'
    )
);

author-model:

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());
}

debug($book) in my wiev.ctp give these results:

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
            )

    )

)

I belive the [0][1] index in the array are the problem. I've searched the problem, and found some articles on the subject, but can't get any of the solutions to work开发者_开发技巧.

Any help is greatly appreciated. I am using cakephp 1.3.3

Thanks


You would normally loop over the Author array, since you can have a varying number of authors.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜