Yii 查询 搜索

Posted __Rain丶

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Yii 查询 搜索相关的知识,希望对你有一定的参考价值。

一、视图

     

<div class="form-horizontal">
    <?php $form = $this->beginWidget(‘CActiveForm‘, array(‘id‘ => ‘course‘, ‘action‘ => ‘/admin/mp/‘)); ?>
    <div class="form-group">
        <div class="col-md-2">
            <?php echo $form->textField($model, ‘title‘, array(‘class‘ => ‘form-control‘, ‘placeholder‘ => ‘标题‘)); ?>
        </div>
        <div class="col-md-2">
            <?php echo $form->textField($model, ‘name‘, array(‘class‘ => ‘form-control‘, ‘placeholder‘ => ‘名字‘)); ?>
        </div>
        <div class="col-md-2">
            <?php echo $form->dropDownList($model, ‘type‘, array(‘‘ => ‘类别‘) + $model->getTypeList(), array(‘class‘ => ‘form-control‘, ‘placeholder‘ => ‘类别‘)); ?>
        </div>
        <div class="col-md-1">
            <?php echo Chtml::submitButton(‘查询‘, array(‘class‘ => ‘btn btn-default btn-primary‘)); ?>
        </div>
        <div class="col-md-1">
            <a href="/admin/user/edit" class="btn btn-default">添加矩阵</a>
        </div>
    </div>
    <?php $this->endWidget(); ?>
</div>

 

二、模型

class Mp extends CActiveRecord
{

    const AFFAIRS  = 1;
    const BUSINESS = 2;

    public function tableName()
    {
        return ‘mp‘;
    }

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function getTypeList()
    {
        return array(
            self::AFFAIRS => ‘政务‘,
            self::BUSINESS => ‘商业‘,
        );
    }

    public function getTypeName()
    {
        $arr = $this->getTypeList();
        if (isset($arr[$this->type])) {
            return $arr[$this->type];
        }
        return ‘未知‘;
    }
    public function rules()
    {
        return array(
            array(‘title,name,type‘, ‘safe‘, ‘on‘ => ‘search‘),
        );
    }

}

 

三、控制器

 public function actionIndex()
    {
        $model = new Mp(‘search‘);
        if (isset($_POST[‘Mp‘])) {
            $model->setAttributes($_POST[‘Mp‘]);
        }
        $criteria = new CDbCriteria();
        $criteria->addSearchCondition(‘title‘, $model->title);
        $criteria->addSearchCondition(‘name‘, $model->name);
        $criteria->addSearchCondition(‘type‘, $model->type);
        $count = Mp::model()->count($criteria);
        $pager = new CPagination($count);
        $pager->pageSize = $this->pageSize;
        $pager->applyLimit($criteria);

        $list = Mp::model()->findAll($criteria);
        $this->render(‘index‘,array(‘model‘=>$model,‘list‘=>$list,‘pager‘=>$pager));

    }

 

以上是关于Yii 查询 搜索的主要内容,如果未能解决你的问题,请参考以下文章

Yii2 - 活动记录查询搜索字符串字段中的数字

Yii2框架学习 4-1 modelSearch类学习 自定义搜索,关联查询

Yii2片段缓存详解

Yii2 从表单获取用户输入

yii2中关联查询

Yii Framework使用DAO方式查询分页代码