如何在视图中显示HABTM关系的结果? [英] How to display results from a HABTM relationship in a view?

查看:98
本文介绍了如何在视图中显示HABTM关系的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在books表和authors表之间有HABTM关系,并与authors_books表一起加入。
然而,我找不到一个解决方案来显示我的视图中的firstname,lastname和fullname。

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:

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'
    )
);

作者模型:

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:

books_controller:

   function view($id) {
    $this->Book->id = $id;
    $this->set('book', $this->Book->read());
}



在我的wiev.ctp中调试($ book) p>

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
            )

    )

我相信[0] [1] ]索引在数组中的问题。
我搜索了这个问题,发现了一些关于这个问题的文章,但是找不到任何解决方案。

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.

赞赏。我使用cakephp 1.3.3

Any help is greatly appreciated. I am using cakephp 1.3.3

感谢

推荐答案

通常循环作者数组,因为你可以有不同数量的作者。

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>

这篇关于如何在视图中显示HABTM关系的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆