[英]Selecting from table in different controller in cakephp
In my Users controller I'm trying to display a given users's posts in their profile. 在我的“用户”控制器中,我试图在其个人资料中显示给定用户的帖子。 How can I accomplish this?
我该怎么做? Basically, I'm in the Users controller trying to access the Posts table
基本上,我在Users控制器中尝试访问Posts表
These are my Tables 这些是我的桌子
//Posts
id | body | user_id
//Users
user_id | username
This is my profile function of my users 这是我的用户个人资料功能
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>
I'm getting several "undefined index errors" in reference to each line of profle.ctp 我在参考profle.ctp的每一行时都遇到了几个“未定义的索引错误”
Undefined index: Post [APP/View/Users/profile.ctp, line 11]
In your UsersController
on your profile
action, you can use the User
model to access associated information. 在您的
profile
操作上的UsersController
,您可以使用User
模型访问关联的信息。
Example: 例:
class UsersController extends AppController {
public function profile($id = null) {
$this->User->recursive = 2;
$this->set('user', $this->User->read(null, $id));
}
}
In your User
and Post
model, you should have the correct associations setup: 在
User
和Post
模型中,您应该具有正确的关联设置:
User
model: User
模型:
class User extends AppModel {
public $hasMany = array('Post');
}
Post
model: Post
模型:
class Post extends AppModel {
public $belongsTo = array('User');
}
You will see now that in your view, on the $user
variable, you have all the user data for the specified profile id, along with associated posts for that user. 现在,您将在视图中的
$user
变量上看到具有指定配置文件ID的所有用户数据,以及该用户的关联帖子。
This page in the CakePHP documentation has some great helpful tips in reading your data from models. CakePHP文档中的此页面提供了一些非常有用的提示,可帮助您从模型中读取数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.