从cakepp中不同控制器的表格中进行选择


Selecting from table in different controller in cakephp

在我的用户控制器中,我试图在给定用户的配置文件中显示他们的帖子。我怎样才能做到这一点?基本上,我在用户控制器中试图访问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>

我在引用prov.ctp 的每一行时都会遇到几个"未定义的索引错误"

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

profile操作的UsersController中,您可以使用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文档中的这个页面有一些从模型中读取数据的非常有用的提示。