如何在 Yii 中添加搜索和过滤条件

How to add Search and Filter Criteria in Yii

我正在使用 Yii 框架开发数据库应用程序。我正在从 MySQL 数据库读取 tables 并将它们显示给用户。我需要用户能够过滤 table 中的字段或搜索某个值。

例如,我有一个名为 "supermarkets":

的 table
CREATE TABLE IF NOT EXISTS `supermarkets` (
  `Name` varchar(71) NOT NULL,
  `Location` varchar(191) DEFAULT NULL,
  `Telephone` varchar(68) DEFAULT NULL,
  `Fax` varchar(29) DEFAULT NULL,
  `Website` varchar(24) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

.../model/supermarkets:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class Supermarkets extends ActiveRecord
{



}

.../views/supermarkets/index.php:

<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<?php
$array = (array) $supermarkets;

function build_table($array){

    // start table

    $html = '<table class="altrowstable" id="alternatecolor">';

    // header row

    $html .= '<tr>';

    foreach($array[0] as $key=>$value){

            $html .= '<th>' . $key . '</th>';

        }

    $html .= '</tr>';

    // data rows

    foreach( $array as $key=>$value){

        $html .= '<tr>';

        foreach($value as $key2=>$value2){

            $html .= '<td>' . $value2 . '</td>';

        }

        $html .= '</tr>';

    }

    // finish table and return it

    $html .= '</table>';

    return $html;

}



echo build_table($array);

?>

.....Controllers/SupermarketsController:

<?php

namespace app\controllers;

use yii\web\Controller;

use yii\data\Pagination;
use app\models\Supermarkets;
class SupermarketsController extends Controller
{
    public function actionIndex()
    {
        $query = supermarkets::find();

        $pagination = new Pagination([
            'defaultPageSize' => 20,
            'totalCount' => $query->count(),
        ]);

        $supermarkets = $query->orderBy('Name')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();

        return $this->render('index', [
            'supermarkets' => $supermarkets,
            'pagination' => $pagination,
        ]);
    }
}

我需要用户能够过滤 table 或按一个或多个属性搜索其字段。我该怎么做?

在模型 class 而不是控制器中组织所有查询和过滤的正确且更好的方法。

您应该使用 findAll() 而不是 find() - 来查找符合您条件的所有记录。 find() - 仅限于 return 一条记录。

您可以通过不同的方式完成您需要的工作:

  1. 只需创建字符串 SQL-条件来搜索必要的属性:

    findAll('Name = "Supermarket" OR Telephone = "99988899"')

// 使用名称 "Supermarket" 或电话搜索超市 - “99988899”(不带引号)

  1. Yii 使用 CDbCriteria 的好方法:

$criteria = new CDbCriteria(); // 添加任何你想过滤的属性 $criteria->addCondition('Name = "Supermarket"'); $criteria->addCondition('Telephone = "99988899"','OR');

并像 findAll($criteria) 一样使用 findAll。

最后 - 请阅读有关模型和使用 ActiveRecord 的 Yii 手册。它的文档非常好并且易​​于理解。

无需重新发明轮子,您可以简单地使用提供的 Yii CGridView widget。它具有排序和过滤功能。查看文档,您会发现有很多配置可供您使用。以下代码片段使用最低配置。

.../views/supermarkets/index.php:

    <?php
    $this->widget('zii.widgets.grid.CGridView', array(
        'id' => 'supermarkets-grid',
        'dataProvider' => $model->search(),
        'filter' => $model,
        'columns' => array(
            'name',
            'location',
            'telephone',
            'fax',
            'website'
        ),
    ));
    ?>

在超市模型中实现 search() 函数。

public function search()
{

    $criteria=new CDbCriteria;

    $criteria->compare('name',$this->name,true);
    $criteria->compare('location',$this->location,true);
    $criteria->compare('telephone',$this->telephone,true);
    $criteria->compare('fax',$this->fax,true);
    $criteria->compare('website',$this->website,true);

    return new CActiveDataProvider(get_class($this), array(
        'criteria'=>$criteria,
        'sort'=>array(
            'defaultOrder'=>'name ASC',
        ),
        'pagination'=>array(
            'pageSize'=>20
        ),
    ));
}

Controllers/SupermarketsController:.

public function actionIndex() {
    $model =new Supermarkets('search');
    if(isset($_GET['Supermarkets']))
        $model->attributes =$_GET['Supermarkets'];

    return  $this->render('index', array('model'=>$model));
}