【问题标题】:Search a specific database field with CakePHP post method使用 CakePHP 的 post 方法搜索特定的数据库字段
【发布时间】:2011-03-02 16:13:38
【问题描述】:

我正在尝试在应用程序中实现一个简单的搜索,但不确定处理这个问题的最佳方法。我的数据库包含一个包含 City 字段的 Listings 对象。我想创建一个搜索表单,用户在文本字段中输入一个城市,并在下一页上获取该城市的所有列表。我不想执行全文搜索,只执行对该 City 字段的查询。

另外,在结果页面上,我想将查询存储在 POST 中,但不知道最好的方法。

在控制器中处理此问题的最佳方法是什么?

【问题讨论】:

  • 我建议你从这个问题开始:)

标签: php search cakephp


【解决方案1】:

那么你的视图应该是这样的

$this->Form->Create('Listing', array('action'=>'search'));
$this->Form->input('city', array('default'=>$city));
$this->Form->end();

if (isset($listings)) {
//code to display listings
}

此视图将创建正确的表单。而您的控制器需要获得该值

function search() {
   $city = '';
   if (!empty($this->data)) {
      $city  = $this->data['Listing']['city'];
      $opts  = array(
          'conditions' => array('Listing.city' => $city)
      );
      $listings   = $this->Listing->find('all', $opts); 
      $this->set('listings', $listings);
   }
   $this->set('city', $city); // so the keyword is saved. Can also get it via $this->data
}

此代码应该让您了解如何执行此操作。

【讨论】:

    【解决方案2】:

    这是一个很棒的教程,带有 CakePHP search plugin 教程。您也可以从github(带有 MySQL 转储)下载完整的工作代码。

    【讨论】:

      【解决方案3】:

      查看:

      <?php echo $this->Form->create() 
      
      echo $this->Form->input('search');
      
      ?>
      
      <input name="data[Product][word]" />
      

      控制器:

      <?php 
      
          $result = $this->Product->find('all',array(
              'conditions'=>array(
                  'OR'=>array(
                      array('name LIKE'=>'%'.$word.'%'),
                      array('description LIKE'=>'%'.$word.'%'))))); 
      
      
          $this->set(compact('result'));
      
      ?>
      

      【讨论】:

      • 解释你的代码。这是最好的方式(如所问)?为什么?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 2020-02-28
      • 2014-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多