1

我已经阅读了 CakeBook 上关于Containable 数组的指南。

class Post extends AppModel {
    public $actsAs = array('Containable');

结果是:

array(
    (int) 0 => array(
        'Post' => array(
            'id' => '1',
            'title' => 'This is the first post',
            'slug' => 'this-is-the-first-post',
            'body' => 'body body 111body body 111body body 111body body 111body body 111body body 111body body 111',
            'image_id' => '0',
            'language' => 'sv',
            'translation_id' => '0',
            'created' => '2012-09-03 17:45:57',
            'modified' => '2012-09-03 19:12:21'
        ),
        'Image' => array(
            'id' => null,
            'name' => null,
            'url' => null,
            'alt' => null,
            'description' => null
        ),
        'Asset' => array(),
        'Readmore' => array(),
        'Reference' => array(),
        'Category' => array(),
        'Course' => array(),
        'Tag' => array(),
        'User' => array(
            (int) 0 => array(
                'password' => '*****',
                'id' => '2',
                'username' => 'test0',
                'fullname' => 'Test Test',
                'url' => '',
                'email' => '',
                'role' => 'admin',
                'phone' => '+',
                'created' => '2012-09-03 17:44:22',
                'PostsUser' => array(
                    'id' => '1',
                    'post_id' => '1',
                    'user_id' => '2'
                )
            ),
            (int) 1 => array(
                'password' => '*****',
                'id' => '1',
                'username' => 'test1',
                'fullname' => 'Frank',
                'url' => '',
                'email' => '',
                'role' => 'admin',
                'phone' => '',
                'created' => '2012-09-03 17:41:25',
                'PostsUser' => array(
                    'id' => '3',
                    'post_id' => '1',
                    'user_id' => '1'
                )
            )
        )
    ),

但是打印出数组的特定部分是行不通的。因此,如果我在 Post 的索引视图中,我会写:

echo h($post['Post']['title']);

一切都很好,但是当我尝试时:

echo h($post['User']['fullname']); 

它不起作用。我明白了,当我在帖子和用户之间有一个 hasmany 和 belgosto 关系时,我必须遍历用户。

那么如何打印与帖子关联的所有用户?

4

2 回答 2

2

欢迎来到堆栈溢出!

$post['User']是一个用户数组,因此,每个用户都有一个索引,例如,要获取test0´s全名,您需要执行以下操作:

echo h($post['User'][0]['fullname']);

尝试以下操作以显示所有用户的全名:

<?php
foreach($post['User'] as $user) { 
    echo h($user['fullname']);
});
于 2012-09-11T18:08:30.123 回答
1

谢谢!我找到了解决方案。我有点粗心,我之前尝试了一个手动完成的解决方案,并为该模型添加了一个 PostUser 模型和一个控制器。删除它们,一切正常。蛋糕魔法再次起作用。

于 2012-09-12T07:36:57.973 回答