我想通过搜索输入从数据库中搜索我的数据,一切正常但我无法找到为什么这段代码不起作用。当我在输入框中输入搜索数据时,任何事情都已完成。请帮助
我的控制器:AdUnitsController
class AdUnitsController extends AppController
{
public function index()
{
$query = $this->_getData();
$this->set('adUnits', $this->paginate($query));
$this->paginate = [
'contain' => ['Networks', 'Games', 'AdTypes']
];
$adUnits = $this->paginate($this->AdUnits);
$this->set(compact('adUnits'));
$this->set('_serialize', ['adUnits']);
}
public function _getData()
{
if (!empty($this->request->data['search'])) {
$search = $this->request->data['search'];
$query = $this->AdUnits->find('All')->where([
'OR' => [
['name LIKE' => '%' . $search . '%'],
],
]);
}
else{
$query = $this->AdUnits->find('All');
}
return $query;
}
我的观点index.ctp:
<label> Search</label>
<?php echo $this->Form->create('AdUnits',array('id' => 'site-search','url'=>array('action'=>'index')));?>
<div>
<?php echo $this->Form->input('search',array('class' => 'form-control', 'label' =>false, 'placeholder' => 'Type Network')); ?>
</div>
<div> <button type="submit"> Search</button>
<?php echo $this->Form->end();?>
搜索不起作用。请帮助
答案 0 :(得分:1)
首先简化您的代码:您没有理由做两个分页
public function index()
{
$this->paginate = [
'contain' => ['Networks', 'Games', 'AdTypes']
];
$query = $this->_getData();
$this->set('adUnits', $this->paginate($query));
}
如果您仍然遇到问题,可能是您的查询中有错误。我的猜测是,name
列是不明确的,所以请在find()
来电
['AdUnits.name LIKE' => '%' . $search . '%']
作为附注,我建议您阅读文档,特别是学习如何调试代码。
在我看来,_getData
方法也应该移到模型或组件中。
答案 1 :(得分:0)
public function index()
{
$query = $this->_getData();
$this->set('adUnits', $this->paginate($query));
$this->paginate = [
'contain' => ['Networks', 'Games', 'AdTypes']
];
$adUnits = $this->paginate($this->AdUnits);
$this->set(compact('adUnits'));
$this->set('_serialize', ['adUnits']);
}
替换为
public function index()
{
$this->paginate = [
'contain' => ['Networks', 'Games', 'AdTypes']
];
$query = $this->_getData();
$this->set('adUnits', $this->paginate($query));
}