Tuesday, November 29, 2011

Access Data in Associations Efficiently

Hi all,

I've managed to set up most of my associations and models in CakePHP (I'm a noobie).
Now I have a very basic question. Let me explain the situation first.
I have got a User, Pet and Post model.
The user hasmany pets, the pet hasmany posts.
The user can also log in. 

Now in my controller, I want to access the Posts of the pets of the current user.
To do this, I'm using the following method, which I think is not really what I'm looking for:

#in user.php (model)

public function getPosts($uid = null){
$user = $this->findById($uid);
$pets = $user['Pet'];
$result = array();
foreach ($pets as $pet){
$pett = $this->Pet->findById($pet['id']);
$result = array_merge($result, $pett['MyFeed']);
}
return $result;
}

#in my controller

$feed = $this->User->getPosts($this->Auth->user('id'));

Not only can i not order my posts correctly (by date), but I also think this is not the way to go.
Do you have any suggestions on doing this better? Isn't it possible to store the logged in User somewhere so that accessing it's associations is easier? 

Thanks in advance,

Jordy


--
Our newest site for the community: CakePHP Video Tutorials http://tv.cakephp.org
Check out the new CakePHP Questions site http://ask.cakephp.org and help others with their CakePHP related questions.
 
 
To unsubscribe from this group, send email to
cake-php+unsubscribe@googlegroups.com For more options, visit this group at http://groups.google.com/group/cake-php

No comments: