CakePHP Find Related Data
-
27-10-2019 - |
Question
My Gallery model is related to my image model, but when I retrive images from galleries_controller I cant see any result and instead see this error:
Warning (2): Invalid argument supplied for foreach() [APP\views\galleries\view.ctp, line 35]
Here is the code from my controller action:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid gallery', true));
$this->redirect(array('action' => 'index'));
}
$this->set('gallery', $this->Gallery->read(null,$id));
$this->Gallery->Image->find('all',array('conditions' => array('Image.gallery_id'=> $id)));
$this->set('images', $images);
}
This is the loop I have in my galleries/view to iterate through the array.
<?php
$i = 0;
foreach ($images['Image'] as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php $image['id'] ;?></td>
<td><?php echo $image['name'];?></td>
<!--<td><?php echo $image['img_file'];?></td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['img_file'], array('alt' => 'Gallery Image')); ?></td>
</tr>
<?php endforeach; ?>
Solution
You aren't setting anything with your set. Your find is being executed and then not stored in a variable. Furthermore, your view loop is iterating through incorrectly.
Change your controller to:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid gallery', true));
$this->redirect(array('action' => 'index'));
}
$this->set('gallery', $this->Gallery->read(null,$id));
$images = $this->Gallery->Image->find('all',array('conditions' => array('Image.gallery_id'=> $id)));
$this->set('images', $images);
}
And your view code to:
<?php
$i = 0;
foreach ($images as $image):
$class = null;
if ($i++ % 2 == 0) {
$class = ' class="altrow"';
}
?>
<tr<?php echo $class;?>>
<td><?php $image['Image']['id'] ;?></td>
<td><?php echo $image['Image']['name'];?></td>
<!--<td><?php echo $image['Image']['img_file'];?></td>-->
<td><?php echo $html->image('uploads' . DS . 'images' . DS . $image['Image']['img_file'], array('alt' => 'Gallery Image')); ?></td>
</tr>
<?php endforeach; ?>
That having been said, since all you want to do is pull in associated images when a gallery is viewed, you should look into setting up your model associations and then doing a find on your gallery that will include the images you want like so:
$this->set('gallery',$this->Gallery->find('first', array('conditions' => array('Gallery.id' => $id), 'recursive' => 1));
If the above don't work, then there is something misconfigured in your models. Please post your model code so we can investigate further.