2012-02-02 34 views
0

我有一個模型Tasklist,並且每個Tasklist項目都屬於一個Service項目。CakePHP - 使用group by來打印單個表格標題

在我的任務列表控制器:

function index() { 
    $this->Tasklist->recursive = 0; 
    $this->set('tasklists', $this->Tasklist->find('all', array(
    'order' => array(
     'Service.name' => 'ASC', 
     'Tasklist.name' => 'ASC' 
    ) 
))); 
} 
我簡單的索引視圖

相關部分:

<?php foreach ($tasklists as $tasklist): ?> 
    <tr> 
     <td><?php echo $tasklist['Tasklist']['id']; ?></td> 
     <td><?php echo $tasklist['Tasklist']['name']; ?></td> 
     <td> 
     <?php echo $this->Html->link($tasklist['Service']['name'], array('controller' => 'services', 'action' => 'view', $tasklist['Service']['id'])); ?> 
     </td> 
     <td><?php echo $tasklist['Tasklist']['created']; ?></td> 
     <td><?php echo $tasklist['Tasklist']['modified']; ?></td> 
     <td> 
     <?php echo $this->Html->link(__('Edit', true), array('action' => 'edit', $tasklist['Tasklist']['id']), array('class' => 'button edit')); ?> 
     </td> 
    </tr> 
<?php endforeach; ?> 

而不是每個表格行的打印服務名稱,我想打印出來作爲與任務列表分組在每個下面:

<tr> 
     <th colspan="5"><?php echo $this->Html->link($tasklist['Service']['name'], array('controller' => 'services', 'action' => 'view', $tasklist['Service']['id'])); ?></th> 
</tr> 
<tr> 
     <td><?php echo $tasklist['Tasklist']['id']; ?></td> 
     <td><?php echo $tasklist['Tasklist']['name']; ?></td> 
     <td><?php echo $tasklist['Tasklist']['created']; ?></td> 
     <td><?php echo $tasklist['Tasklist']['modified']; ?></td> 
     <td> 
     <?php echo $this->Html->link(__('Edit', true), array('action' => 'edit', $tasklist['Tasklist']['id']), array('class' => 'button edit')); ?> 
     </td> 
</tr> 

我已經嘗試過使用組p參數在我的控制器和嵌套的foreach在我看來,但不能得到它的工作。

回答

1

我會做這樣的

$current_service = ''; 
    <?php foreach ($tasklists as $tasklist): ?> 
    <?php if($current_service != $tasklist['Service']['name']): ?> 
    <tr> 
      <th colspan="5"><?php echo $this->Html->link($tasklist['Service']['name'], array('controller' => 'services', 'action' => 'view', $tasklist['Service']['id'])); ?></th> 
    </tr> 
    <?php $current_service = $tasklist['Service']['name']; ?> 
    <?php endif; ?> 
    <tr> 
      <td><?php echo $tasklist['Tasklist']['id']; ?></td> 
      <td><?php echo $tasklist['Tasklist']['name']; ?></td> 
      <td><?php echo $tasklist['Tasklist']['created']; ?></td> 
      <td><?php echo $tasklist['Tasklist']['modified']; ?></td> 
      <td> 
      <?php echo $this->Html->link(__('Edit', true), array('action' => 'edit', $tasklist['Tasklist']['id']), array('class' => 'button edit')); ?> 
      </td> 
    </tr> 

    <?php endforeach; ?> 
+0

啊,完美。謝謝。 – randomswathe 2012-02-02 21:09:16