在cakephp中从不同控制器的表中选择
在我的用户控制器中,我试图在他们的个人资料中显示给定用户的帖子。我怎样才能做到这一点?基本上,我在用户控制器中尝试访问Posts表 这些是我的桌子在cakephp中从不同控制器的表中选择,php,mysql,cakephp,Php,Mysql,Cakephp,在我的用户控制器中,我试图在他们的个人资料中显示给定用户的帖子。我怎样才能做到这一点?基本上,我在用户控制器中尝试访问Posts表 这些是我的桌子 //Posts id | body | user_id //Users user_id | username 这是我的用户配置文件功能 UsersController.php public function profile($id = null) { $this->User->id = $id; if (!$
//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>
在您的
userscoontroller
中,您可以使用User
模型访问相关信息
例如:
class UsersController extends AppController {
public function profile($id = null) {
$this->User->recursive = 2;
$this->set('user', $this->User->read(null, $id));
}
}
在您的User
和Post
模型中,您应该具有正确的关联设置:
用户
型号:
class User extends AppModel {
public $hasMany = array('Post');
}
class Post extends AppModel {
public $belongsTo = array('User');
}
Post
型号:
class User extends AppModel {
public $hasMany = array('Post');
}
class Post extends AppModel {
public $belongsTo = array('User');
}
现在您将看到,在视图中,在$user
变量上,您拥有指定配置文件id的所有用户数据,以及该用户的相关帖子
在从模型中读取数据时有一些非常有用的提示