在CakePHP应用程序中,我有3个表(2个表和1个联结表):
task_types[id, name], task_type_groups[id, name], (junction table) task_types_task_types_group[id, task_type_id, task_types_group_id]
我想在我的视图中填充一个表,并在用户选择task_type_group
时对其进行过滤。
所以在视图中,我为过滤器和表格提供了以下代码:
<div class="taskElements index large-9 medium-8 columns content">
<div class="row">
<?php echo $this->Form->create('AddTaskTypeToProject', array('action' => 'index')); ?>
<?php echo $this->Form->control('task_type_groups', ['options' => $taskTypeGroups, 'empty' => true]); ?>
<?php echo $this->Form->button(__('Filter'), ['class'=>'btn-success']); ?>
<?php echo $this->Form->end(); ?>
</div>
<h3><?= __('Task Type Groups') ?></h3>
<?php echo $this->Form->create('AddTaskTypeToProject', ['url'=>['action' => 'add']]); ?>
<table cellpadding="0" cellspacing="0">
<thead>
<tr>
<th scope="col"><?= $this->Paginator->sort('id') ?></th>
<th scope="col"><?= $this->Paginator->sort('name') ?></th>
<th scope="col"><?= $this->Paginator->sort('select') ?></th>
<th scope="col"><?= $this->Paginator->sort('task_types_group_id') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($taskTypes as $id => $taskType): ?>
<tr>
<td><?= $this->Number->format($taskType->task_type->id) ?></td>
<td><?= $taskType->task_type->name ?></td>
<?= $this->Form->hidden("$id.id",['value' => $taskType->task_type->id]); ?>
<?= $this->Form->hidden("$id.name",['value' => $taskType->task_type->name]); ?>
<td><?= $this->Form->control("$id.checked", ['type' => 'checkbox']);?></td>
<td><?= $taskType->task_types_group_id != 0 ? $this->Html->link($taskType->task_type_group->name, ['controller' => 'TaskTypeGroups', 'action' => 'view', $taskType->task_type_group->id]) : '' ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table><?php
echo $this->Form->submit('Add');
echo $this->Form->end();?>
</div>
在控制器中:
public function index()
{
if($this->request->is('post'))
{ //filtering works as expected
if($this->request->getData('task_type_groups') != null){
$taskTypes = TableRegistry::get('TaskTypesTaskTypesGroups')
->find('all', [
'conditions' => ['TaskTypesTaskTypesGroups.task_types_group_id' => $this->request->getData('task_type_groups')],
'contain' => ['TaskTypes', 'TaskTypeGroups']
]);
}
else{ //this is not working
$taskTypes = TableRegistry::get('TaskTypesTaskTypesGroups')
->find('all', [
'contain' => ['TaskTypes', 'TaskTypeGroups']
]);
}
$this->set(compact('taskTypes'));
}
else
{
$taskTypes = TableRegistry::get('TaskTypes')->find('all', [
'contain' => ['TaskTypesTaskTypesGroups']
]);
$this->set(compact('taskTypes'));
}
$taskTypeGroups = TableRegistry::get('TaskTypeGroups')->find('list');
$this->set(compact('taskTypeGroups'));
}
如果用户过滤该表,则该表有效,并且我仅获得属于所选组的task_types。但是,如果过滤器为空,那么我不会获得与任何组相关联的task_types。所以我想转换这个:
$taskTypes = TableRegistry::get('TaskTypesTaskTypesGroups')
->find('all', [
'contain' => ['TaskTypes', 'TaskTypeGroups']
]);
到outer join
中,它将返回所有task_type(无论它们是否属于task_type_group)