CakePHP Get data from a distant relationship
The following is an example and not used in my app but I hope to get the theory and apply it to my own application after getting the answerer.
So take a simple app with 3 tables: Users, Locations, and Posts
and the relationships are a Post has a User and a User has a Location but a Location doesn't necessarily have a User.
If I pull a list of Posts and then show the User of that Post this is fine. But what If I wanted to pull the Location of the User? As their is no relation between the Post and the Location but their is one between the User and the Post. How would I do it?
Example of the loop:
<?php foreach($posts as $post): ?>
<?php echo $this->Html->link($post['User']['firstname'], array('controller'=>'users','action'=>'view','userName'=>$post['User']['username'])); ?> in <?php echo $this->Html->link($post['Place']['name'], array('controller'=>'开发者_运维问答places','action'=>'view',$post['Place']['id'])); ?>
and this is the controller:
function index()
{
$posts = $this->paginate();
if (isset($this->params['requested']))
{
return $posts;
}
else
{
$this->set('posts', $posts);
}
}
Now this would not work as Place is undefined! How do I do it?
I have heard Containable
mentioned but some examples would be great!
Have a look at the containable behaviour. Not only will it allow you to solve this problem but it will also help your application performance by ensuring only required data is retrieved, parsed and returned.
e.g.
function index()
{
$this->paginate = array(
'contain' => array('User' => array('Location')),
);
$posts = $this->paginate();
if (isset($this->params['requested']))
{
return $posts;
}
else
{
$this->set('posts', $posts);
}
}
精彩评论