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

走远了吗. 提交于 2020-01-14 05:14:27

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/3667997/how-to-display-results-from-a-habtm-relationship-in-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!