0

在我的用户控制器中,我试图在他们的个人资料中显示给定用户的帖子。我怎样才能做到这一点?基本上,我在用户控制器中试图访问 Posts 表

这些是我的桌子

//Posts
id | body | user_id

//Users
user_id | username

这是我的用户的个人资料功能

  UsersController.php

  public function profile($id = null) {
    $this->User->id = $id;
    if (!$this->User->exists()) {  //if the user doesn't exist while on view.ctp, throw error message
        throw new NotFoundException(__('Invalid user'));
    }
    $conditions = array('Posts.user_id' => $id);
    $this->set('posts', $this->User->Posts->find('all',array('conditions' => $conditions))); 
}


/Posts/profile.ctp     

<table>
<?php foreach ($posts as $post): ?>

    <tr><td><?php echo $post['Post']['body'];?>
    <br>

    <!--display who created the post -->
    <?php echo $post['Post']['username']; ?>
    <?php echo $post['Post']['created']; ?></td>
</tr>
<?php endforeach; ?>
</table>

关于profle.ctp 的每一行,我都收到了几个“未定义的索引错误”

Undefined index: Post [APP/View/Users/profile.ctp, line 11]
4

1 回答 1

1

在您UsersControllerprofile操作中,您可以使用User模型来访问相关信息。

例子:

class UsersController extends AppController {
    public function profile($id = null) {
        $this->User->recursive = 2;
        $this->set('user', $this->User->read(null, $id));
    }
}

在您的UserPost模型中,您应该具有正确的关联设置:

User模型:

class User extends AppModel {
    public $hasMany = array('Post');
}

Post模型:

class Post extends AppModel {
    public $belongsTo = array('User');
}

现在您将看到,在您的视图中,在$user变量上,您拥有指定配置文件 ID 的所有用户数据,以及该用户的相关帖子。

CakePHP 文档中的这个页面在从模型中读取数据时提供了一些非常有用的技巧。

于 2012-08-06T01:11:00.663 回答