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
UsersControlleron yourprofileaction, you can use theUsermodel to access associated information.Example:
In your
UserandPostmodel, you should have the correct associations setup:Usermodel:Postmodel:You will see now that in your view, on the
$uservariable, 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.