我有一个模型Tasklist,每个Tasklist项都属于一个Service项。
在我的Tasklist控制器中:
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,但无法使其工作。
答案 0 :(得分: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; ?>