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
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
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.
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
model:
class User extends AppModel {
public $hasMany = array('Post');
}
Post
model:
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.
This page in the CakePHP documentation has some great helpful tips in reading your data from models.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.