CakePHP-使用groupby打印单个表头


CakePHP - Using group by to print single table headers

我有一个模型Tasklist,每个Tasklist项都属于一个Service项。

在我的任务列表控制器中:

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>

我曾尝试在控制器中使用group参数,并在视图中使用嵌套foreach,但无法使其发挥作用。

我会像这个一样做

   $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; ?>