Search code examples
mysqlcakephp-2.1distinct-values

CakePHP 2.1 Select Distinct field but still select the ID in the SQL table


Hi Im making a gallery on my news website for my portfolio having a minor glitch however. I'm trying to select a distinct gallery so that it doesn't repeat itself, this is the code I have so far

function viewgalleries() {

    $viewgalleries = $this->Gallery->find('all', array(
        'fields' => 'DISTINCT Gallery.gallery_name'));
    if (!empty($this->request->params['requested'])) {
return $viewgalleries; }
    $this->set('gallery', $viewgalleries); 

}

and this is my view..

     <?php $viewgalleries = $this->requestAction('/Galleries/viewgalleries');?>

    <div class="allgalleries">

 <table class="galleries">
<?php foreach ($viewgalleries as $galleries): ?>
    <tr>
       <td>
         <span class="gallerylink">
            <?php echo $this->Html->link($galleries['Gallery']['gallery_name'], 
                  array('controller' => 'Gallery', 'action' => 'view', 
                  $galleries['Gallery']['id'])); ?>
         </span>
       </td>
    </tr>
  <?php endforeach; ?>
  </table>
    </div>

This gives me want I want however it isn't selecting the id field in the table so its throwing me this error...

  Notice (8): Undefined index: id [APP/View/Galleries/viewgalleries.ctp, line 10]

Below it does show me the name of the gallery however Champions League Final 2012

Any ideas as to how I could still select the id from the database??

Thanks in advance or any help.


Solution

  • Instead of using the select distinct function as it proved to be quite tricky I instead decided to re-format my gallery my adding validation techniques such isUnique in order to let allow the passing of the same gallery name, this was achieved in the Models/Gallery.php with the following statement:

    public $validate = array(
        'gallery_name' => array(
            'rule' => 'isUnique',
            'message' => 'This gallery already exists.'));
    

    Hope this helps others.