CakePHP Relation on link
The following link is used in a list of Favours! It links to a place where the user is from but is being used inside the favour lis开发者_JAVA百科t Hence the favour variable.
I have three models Users, Places and Favours. A user has many favours and one place, a favour belongs to a user.
<?php foreach($favours as $favour): ?>
<p><?php echo $this->Html->link($favour['User']['firstname'] . ' ' . $favour['User']['lastname'], array('controller'=>'users','action'=>'view','userName'=>$favour['User']['username'])); ?> in <?php echo $this->Html->link($favour['Place']['name'], array('controller'=>'places','action'=>'view',$favour['Place']['id'])); ?> asked a favour <?php echo $favour['Favour']['datetime']; ?></p>
<h3><?php echo $this->Html->link($favour['Favour']['title'], array('controller'=>'favours','action'=>'view',$favour['Favour']['id'])); ?></h3>
How do I display the link as at the moment I get an error saying that Place is undefined.
This is the controller action for that list:
function index()
{
$favours = $this->paginate();
if (isset($this->params['requested']))
{
return $favours;
}
else
{
$this->set('favours', $favours);
}
}
Make sure you contain Place when fetching data for Favour.
This is how it should look like in your favours_controller:
function index(){
$favours = $this->Favour->find('all');
$places = $this->Favour->Place->find('all');
$this->paginate();
$this->set(compact('users', 'places');
}
This is how it should look like in your index.ctp:
<?php foreach($favours as $favour): ?>
<?php echo $this->Html->link($favour['Favour']['username'], array('controller'=>'users','action'=>'view', $favour['Favour']['username'])); ?>
<?php endforeach; ?>
<?php foreach($places as $place): ?>
<?php echo $this->Html->link($place['Place']['place'], array('controller'=>'places','action'=>'view', $place['Place']['place'])); ?>
<?php endforeach; ?>
You may also need to define the uses
variable:
var $uses = array('Place');
精彩评论