YII load()
看上图 其中数组 UniversityPostSearch 是通过前端表单传过来的数据,而我只想验证 这个表单数据是不是合法 应该这样写
$this->load($param,'UniversityPostSearch');
参数 $param 是YII::$app->requist->get() 传过来的所有值 就是上图的 array(3){[id] = .......}
参数 'UniversityPostSearch' 是需要验证的表单
这个加载的好处就是 不用再一步一步的复制 其作用等价于
$this->title = (string)$param['UniversityPostSearch']['title'];
$this->create_time_start = (string)$param['UniversityPostSearch']['create_time_start'];
$this->create_time_end = (string)$param['UniversityPostSearch']['create_time_end'];
$this->status = (int)$param['UniversityPostSearch']['status'];
....
好多行逐一赋值的代码 浓缩为 一行代码 也即
$this->load($param,'UniversityPostSearch');
底层 load() 函数的代码如下图 这就是为什么要传第二个参数的原因
接下来就是rule规则验证的问题
为什么create_time_start 和 create_time_end 需要单独定义一下,而 'is_top', 'title' 不用定义,直接写在 rule()方法 里面了 ??
因为 create_time_start create_time_end 并不是数据库已经存在的字段 如果不写的话 $this->create_time_start 就会报错 说Undifiend create_time_start ..
而 'is_top' , 'title' 是数据库里面的字段,不用定义,就可以 引用 $this->is_top,但是必须要写在rules规则里面,不写错,值为null,赋值就不起作用了。
全部代码如下
<?php
/**
* Created by PhpStorm.
* User: tangwei
* Date: 2018-12-19
* Time: 11:26
*/
namespace business\models\university\search;
use common\models\quan\QuanPost;
use yii\data\ActiveDataProvider;
class UniversityPostSearch extends QuanPost
{
public $create_time_start;
public $create_time_end;
public function rules()
{
return [
[ ['create_time_start', 'create_time_end','title'], 'string'],
[ ['is_top','status','is_essence','sort'] ,'integer'],
];
}
public function search($param,$university){
$query = QuanPost::find()->select('
quan_post.id,
quan_post.title,
quan_post.num_view,
quan_post.num_praise,
quan_post.num_comment,
quan_post.status,
quan_post.create_at,
quan_post.is_top,
quan_topic.title as topic_title,
quan_module.name as module_name,
')
->leftJoin('quan_topic','quan_post.topic_id = quan_topic.id')
->leftJoin('quan_module','quan_post.module_id_school = quan_module.id')
->andWhere(['university_id' => $university]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
]
]);
$this->load($param,'UniversityPostSearch');
if(!$this->validate()){
return $dataProvider;
}
if(!empty($this->title)){
$query->andWhere(['like','quan_post.title', $this->title]);
}
if(!empty($this->create_time_start)){
$query->andWhere(['>=', 'quan_post.create_at', strtotime($this->create_time_start)]);
}
if(!empty($this->create_time_end)){
$query->andWhere(['<=', 'quan_post.create_at', strtotime($this->create_time_end)]);
}
#审核状态
if(is_numeric($this->status)){
$query->andWhere(['quan_post.status' => $this->status]);
}
#是否置顶
if(is_numeric($this->is_top)){
$query->andWhere(['quan_post.is_top' => $this->is_top]);
}
#是否加精
if(is_numeric($this->is_essence)){
$query->andWhere(['quan_post.is_essence' => $this->is_essence]);
}
#排序
if(!empty($this->sort)){
#最热排序
$query->addOrderBy('quan_post.num_view desc');
}else{
#最新排序
$query->addOrderBy('quan_post.create_at desc');
}
return $dataProvider;
}
}