CakePhp Tip #6: Displaying items that belong to a user

cake-logo

Displaying items that belong to a user:

One of the most common things youll do in cakephp is list items that the user should only see. For example a user should just see their “posts” listed or their “articles” etc.

CakePHP has “Magic Find Types” that can help. For example if i wanted to list all the posts of the user_id =12

In my controller i can create an action as follows;

 $myposts=$this->Posts->findAllByUserId(12);

if i wanted to list all posts of the current logged in user;

public function my(){

	$userid=$this->Auth->user('id');
	$this->Post->recursive = 1;
		
	$this->set('posts', $this->paginate('Post',array('Post.user_id =' => $userid)));
		
	//use the index view to render
	$this->render('index');	
 }

To call view this action;

http:://localhost/mycakeapp/posts/my

Source and more info;
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html