【问题标题】:Search function not working - Cakephp搜索功能不起作用 - Cakephp
【发布时间】:2018-06-27 20:57:42
【问题描述】:

我正在使用此操作来搜索用户名

它在我的用户表上运行良好

但是当我尝试在联系表上做同样的事情时 我得到了网址,但它没有检索到结果

ContactController.php

 public function index()
{
  $search = $this->request->query('search');
    if(!empty($search)){
        $this->paginate = [
            'conditions' =>['Contacts.name LIKE '=>'%'.$search. '%']

        ];
    }    
  $this->paginate = [
        'contain' => ['Users', 'Contacts', 'SourceProspects', 'Status', 'Secteurs', 'Products']
    ];
    $contacts = $this->paginate($this->Contacts);
    $this->set(compact('contacts'));
    $this->set('_serialize', ['contacts']);  

}

index.ctp

 <div class="col-md-2 col-sm-2 col-xs-12 form-group top_search">
              <div class="input-group">

                <span class="input-group-btn">
                    <?= $this->Form->create("",['type'=>'get']) ?>
                    <?= $this->Form->control('search', ['default'=>$this->request->getQuery('search'),'class'=>'form-control','placeholder'=>'Search For Name'
                  ]); ?>
                    <button class="btn btn-default ">Go!</button>
                    <?= $this->Form->end() ?>
                                </span>
                </div>
                </div>

我错过了什么?

【问题讨论】:

  • 您的问题到底是什么?空白页?一个空的记录集?您是否启用了调试模式?您是否看到执行了查询?请添加更多信息
  • 我的问题是它没有显示结果需要它显示来自表 localhost/intellix/contacts?search=zak 的所有数据我在这里尝试调试 $search = $this->request->query('search' );它确实显示了结果 zak 但不在我的表格视图中(重定向)它一直显示所有数组

标签: cakephp search


【解决方案1】:

您正在重新分配分页数组(我很确定有类似的问题,但我现在找不到)

事实上当你这样做时

$this->paginate = [
    'contain' => [...]
];

$this->paginate 的值正在重新分配

以下应该可以工作

 $this->paginate = [
    'contain' => [/* your tables here */]
];

if(!empty($search)) {
    $this->paginate['conditions'] =>['Contacts.name LIKE '=>'%'.$search. '%']
}    

但是你可以改进你的代码:

  • $this-&gt;request-&gt;query('search'); 已弃用,请使用 getQuery()
  • 无需在您的视图中使用'default'=&gt;$this-&gt;request-&gt;getQuery('search')。如果您使用 $this-&gt;Form-&gt;create(null, ['valueSources' =&gt; 'query']);,FormHelper 会为您执行此操作,这会告诉 formHelper 使用查询值来填充控件值
  • 最后考虑使用可以完成所有工作的friendsofcake/搜索插件

【讨论】:

    【解决方案2】:

    谢谢你,你是对的 我通过添加 else 来修复

     public function index()
      {
         $search = $this->request->query('search');
    
        if(!empty($search)){
            $this->paginate = [
                'conditions' =>['Contacts.name LIKE '=>'%'.$search. '%']
    
            ];
        }else{
    
        $this->paginate = array(
            'limit' => 4 );
          [
        'contain' => ['Users', 'Contacts', 'SourceProspects', 'Status', 'Secteurs', 
    'Products']
    
        ];
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多