首页 > 学院 > 开发设计 > 正文

YII2.0实战开发小结

2019-11-11 05:26:14
字体:
来源:转载
供稿:网友
 1、$applycar = Applycar::find()->where('{{%applycar}}.complete = 1')->joinWith('car')->joinWith('driver')->asArray()->orderBy('{{%applycar}}.id DESC');如上联合中joinWith('driver')中的driver来自models/Applycar.php中public function getDriver() {return $this->hasOne(Adminer::className(), ['uid' => 'drid']);} public function getCar() {return $this->hasOne(Car::className(), ['id' => 'cid']);}Adminer表中的uid跟Applaycar表中drid相关联 $param = array();if ($param['drname'] = trim($request->get('drname'))) {$applycar->andWhere('{{%adminer}}.truename = "'.$param['drname'].'"');}if ($param['carnumber'] = trim($request->get('carnumber'))) {$applycar->andWhere('{{%car}}.license = "'.$param['carnumber'].'"');}如上:{{%adminer}}指的是表ol_adminer,ol是表前缀car同上$applycar->andWhere用andWhere来连接条件语句if(!empty($param)){//定义获取总公里数$totalkm = $applycar->sum('usekm');//定义获取总加班小时$totalhour = $applycar->sum('overtime');//用sum方法来统计总数:参数为列名}//定义列表查询        $applycar = $applycar->all();$typeArr = array('0'=>'司机','1'=>'自驾');foreach($applycar as $akey => &$aval){$aval['driver'] = Adminer::findOne($aval['drid']);}Adminer::findOne根据参数查询一条语句        return $this->render('record',[            'applycar' => $applycar,'typeArr' => $typeArr,'totalkm' => $totalkm,'totalhour' => $totalhour,'param' => $param,        ]);render第一个参数是views下面的record.php模板文件名'applycar' => $applycar,参数是把值传递到模板applycar2、方法的定义    public function actionAjaxdelapplycar() {必须加前缀action访问的时候是ajaxdelapplycar3、页面跳转的执行return $this->runAction('login');跳转到login页面4、数据的接收        $request = Yii::$app->request;//用对象的形式$applycar = Applycar::findOne($request->post('apid'));$applycar->usekm = $request->post('usekm');$applycar->overtime = $request->post('overtime');$applycar->complete = 1;$applycar->comptime = time();$result = $applycar->save();//保存更新都是save()5、新建控制器放在Controller下所有操作都在Controller下执行即可所有的models下面对应的Applycar.php实体化的表文件 里面一般写一些验证 联合查询等等views就是我们要存储的模板文件以CarsController为例views下面对应的模板文件为cars/文件名对应的render中的第一个参数6、YII引入CSS和JS文件之公共文件路径assets/AppAsset.php7、把变量传递给页面,页面结果作为content变量传递给布局文件  $this->render contoller控制器之间跳转的方法$this->redirect return $this->render('index');//跳转到当前控制器默认的方法 return $this->redirect(array('/cars/dispatch')); //跳转到cars控制器的dispatch方法8、YII原生SQL语句//查询 $connection  = Yii::$app->db;$sql = "...";   $command = $connection->createCommand($sql);  $result  = $command->queryAll(); //更新、删除$upsql = "...";   $command_update = $connection->createCommand($upsql);  $result_update  = $command_update->execute(); if($result_update){    ...}else{    ...} 9、YII模板原生SQL查询  <?phpuse yii/helpers/Html;use yii/bootstrap/ActiveForm;$this->layout = 'XX管理';$this->position = 'XXXX';//查询$result= (new /yii/db/Query())->select(['id' , 'email'])->from('user')->where(['mid' => $member['id']])    ->limit(10) ->all();        //->one();解析为:SELECT `id`, `email` FROM `user` WHERE `mid` = :mid LIMIT 10 ?> 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表