好些个action中的代码是重复的,应该怎么优化调用呢?让代码更加简化 [ 求助交流 ]
public function actionOrder($id=1)
{
$query = Km1::find();
$count = $query->count();
$pager = new Pagination(['totalCount' => $count, 'pageSize' => '1']);
$model = $query->offset($pager->offset)->limit($pager->limit)->all();
//评论部分
$id = $model[0]->courid;
$comments = new Km1Comments();
if($comments->load(Yii::$app->request->post()) && $comments->saveComments() ){
return $this->refresh();
}
$findcomment = Km1Comments::find()->where("cour_id=:id",[":id"=>$id])->orderBy(['order_id'=>SORT_DESC,'created_time'=>SORT_DESC]);
$pages = new Pagination(['totalCount' => $findcomment->count(), 'pageSize' => '5']);
$discuss = $findcomment->offset($pages->offset)->limit($pages->limit)->all();
$title = '顺序练习';
//下一题
$url = Yii::$app->request->getHostInfo().Yii::$app->request->url.'?page=2&per-page=1';
$this->layout = 'practice';
return $this->render('practice',['courses' => $model, 'pager' => $pager,'count'=>$count,'title'=>$title,'comments'=>$comments,'discuss'=>$discuss,'pages'=>$pages,'url'=>$url]);
}
下面的另外一个方法
public function actionRander($id=1)
{
$query = Km1::find();
$count = $query->count();
$arr = $query->select(['courid'])->column();
$pager = new Pagination(['totalCount' => $count, 'pageSize' => '1']);
$result = array_rand($arr,1);
$model = Km1::findAll($result);
//评论部分
$id = $model[0]->courid;
$comments = new Km1Comments();
if($comments->load(Yii::$app->request->post()) && $comments->saveComments() ){
return $this->refresh();
}
$findcomment = Km1Comments::find()->where("cour_id=:id",[":id"=>$id])->orderBy(['order_id'=>SORT_DESC,'created_time'=>SORT_DESC]);
$pages = new Pagination(['totalCount' => $findcomment->count(), 'pageSize' => '5']);
$discuss = $findcomment->offset($pages->offset)->limit($pages->limit)->all();
$title = '随机练习';
//下一题
$url = Yii::$app->request->getHostInfo().Yii::$app->request->url.'?page=2&per-page=1';
$this->layout = 'practice';
return $this->render('practice',['courses' => $model, 'pager' => $pager,'count'=>$count,'title'=>$title,'comments'=>$comments,'discuss'=>$discuss,'pages'=>$pages,'url'=>$url]);
}
考虑到有多个这种方法,希望能做一个模板,然后进行调用,这样代码的数量会简化很多。只是网上找了好久都没找到类似的简化方法。。
共 3 条回复
-
首先你要创建一个模型kmModel
$query = Km1::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, 'sort' =>[ 'defaultOrder'=>['created' => SORT_DESC], ], 'pagination' => [ 'page' => $this->page - 1, // oh, shit. this is zero-base 'pageSize' => $this->pagesize, ], ]) $query->select($this->getSelectFields()) ->andFilterWhere([条件]); return $dataProvider; 控制器里这么写: $kmModel = new kmModel; $dataProvider = $kmModel->search(); if (empty($dataProvider->getModels())) { return '无查询结果'; }
共 1 条回复
且听风吟
注册时间:2017-04-01
最后登录:2019-10-23
在线时长:8小时26分
最后登录:2019-10-23
在线时长:8小时26分
- 粉丝2
- 金钱75
- 威望0
- 积分155