yii2 AR搜索分页 [ 2.0 版本 ]
这个AR搜索分页怎么实现啊
yii2 框架中的一些常用操作,望各位大神指导。
最佳答案
-
``` 首先引入 yii\data\Pagination; 还有各种模型 控制器: new一个AR对象出来 $search = Yii::$app->request->get('search_key'); $where = '1 = 1'; if ($search) { $where .= ' and JName like "%'.$search.'%"'; } $pageArr = $model -> find()->where($where); $pagination = new Pagination(['totalCount' => $pageArr -> count(),'pageSize'=>'3']); $result = $pageArr ->join('INNER JOIN', 'recruit_enterprise','recruit_enterprise.CId = recruit_job.CId') ->select('*') ->offset($pagination ->offset) ->limit($pagination ->limit) ->where($where) ->asArray() ->all(); return $this -> render('job_list', ['result' => $result, 'pagination' => $pagination, ] );
以上是本人个人代码 仅供参考
共 2 条回复@林小陌 public function actionAdd(){
$model = new Fuxi(); $db = Yii::$app->db; if (Yii::$app->request->isPost) { $files = $model->file = UploadedFile::getInstances($model, 'file'); foreach($files as $val){ $list = $val->saveAs('../web/uploads/' . $val->baseName . '.' . $val->extension); } if($list==1){ foreach($files as $v){ $img = $v->name; } $res = $db->createCommand()->batchInsert('fuxi',['uname','content','file'],[[$_POST['Fuxi']['uname'],$_POST['Fuxi']['content'],$img]])->execute(); if($res==1){ $this->redirect(array('hello/show')); } }else{ echo '上传失败'; } } }
其他 10 个回答
-
文件上传 多文件
`控制器 yii\web\UploadedFile; $model->file = UploadedFile::getInstances($model, 'file'); $file_arr = array(); foreach($model -> file as $file){ $file_name = 'uploads/' . time() . rand(111111,999999).'.'. $file->extension; $file -> saveAs($file_name); $file_arr[] = $file_name; } 视图: <?php use yii\widgets\ActiveForm; use yii\helpers\Html; ?> <?php $form=ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data'],'action'=> ['news/upfile'],'method'=>'post',])?> <?=$form->field($model,'file[]')->fileInput(['multiple'=>true])?> <?php echo Html::submitButton('提交',['class' => 'btn btn-primary'])?> <?php ActiveForm::end();?>
`
共 2 条回复@林小陌 public function actionSoso(){
$model = new Fuxi(); $uname = $_GET['uname']; $content = $_GET['content']; $where = '1=1'; if(!empty($uname)){ $where.=" and uname like '%".$uname."%'"; } if(!empty($content)){ $where.=" and content like '%".$content."%'"; } $pagination = new Pagination([ 'defaultPageSize' => 5, 'totalCount' => $model->find()->count(), ]); $list = $model->find() ->offset($pagination->offset) ->limit($pagination->limit) ->where($where) ->asArray()->all(); //print_r($list);die; return $this->render('show',['list'=>$list,'pagination'=>$pagination,'uname'=>$uname,'content'=>$content]); } public function actionXiazai(){ print_r($_SERVER);die; $url = 'http://localhost/Yii/yii/advanced/frontend/web/index.php?r=hello/show'; $list = file_get_contents($url); $filename = rand(0,100).".doc"; $myfile = fopen($filename, "w"); fwrite($myfile, $list); $this->redirect("http://localhost/Yii/yii/advanced/frontend/web/".$filename); }
-
验证码
controller public function actions(){ return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, 'backColor'=>0x000000,//背景颜色 'maxLength' => 6, //最大显示个数 'minLength' => 5,//最少显示个数 'padding' => 5,//间距 'height'=>40,//高度 'width' => 130, //宽度 'foreColor'=>0xffffff, //字体颜色 'offset'=>4, //设置字符偏移量 有效果 //'controller'=>'login', //拥有这个动作的controller ], ]; } model public $verifyCode; public function rules(){ return [ ['verifyCode', 'captcha'] ]; } public function attributeLabels(){ return [ 'verifyCode' => 'Verification Code', ]; } view use yii\captcha\Captcha; ?= $form->field($model, 'verifyCode')->textInput(['class'=>'dl_textinp'])->label('') ?> <?=Captcha::widget(['name'=>'captchaimg','captchaAction'=>'site/captcha', 'imageOptions'=>['id'=>'captchaimg', 'title'=>'换一个', 'alt'=>'换一个', 'style'=>'cursor:pointer;margin-left:25px;'],'template'=>'{image}']);?>
zhangchi 觉得很赞 -
长尾词
view
<?php $form = ActiveForm::begin(['action' => ['work/work_show'],'method'=>'get',]); ?>
<?php ActiveForm::end(); ?>
//向服务器上的search发送post数据,$.post是jQuery的方法 $.post('?r=work/work_search',{'value':val},function(data){ if(data=='0'){ //判断服务器上返回的数据,如果等于0,则表示没有找到相关的内容, //所以将提示框的内容清空并隐藏 $('#search_auto').html('').css('display','none'); }else{ //如果服务器上返回的数据不等于0,则将返回的内容放到提示框内并显示提示框 $('#search_auto').html(data).css('display','block'); } }); $('#search_auto').css({'width':$('#search input[name="search_key"]').width()+6});
}
controller
public function actionWork_search(){ $value = \Yii::$app->request->post('value'); $model = new Job(); $list = $model->find()->where(['like','JName',$value])->asArray()->all(); if(empty($list)){ echo 0;die; } $str=''; $str.= '<ul>'; foreach ($list as $v){ $str.= '<li><a href="?r=work/work_show&search_key='.$v['JName'].'">'.$v['JName'].'</a></li>'; //将查询得到的相关结果的标题输出,这个地方需要注意,由于通过jQuery的ajax技术返回的文本 //是UTF-8编码,所以如果$v['position'] 中包含中文,一定要记得用PHP的iconv或其它函数将其转换 //成UTF-8编码,否则在页面中看到的会是一串乱码 } $str.= '<li class="cls"><a href="javascript:;" onclick="$(this).parent().parent().parent().fadeOut(100)">关闭</a></li>'; //输入一个关闭按钮,让用户不想看到提示层时可以点击关闭,关闭按钮采用jQuery,解释一下, //当前点击的按钮是$(this),一直向上找到其第三个父元素,让它逐渐消失 $str.= '</ul>'; echo $str;die; }
zhangchi 觉得很赞 -
生成缩略图:
2-1、方法及参数说明
\yii\imagine\Image::thumbnail($filename, $width,$height,$mode=ManipulatorInterface::THUMBNAIL_OUTBOUND)//参数说明:
$filename 文件的路径
$width 缩略图的宽
$height 缩略图的高
$mode 模式(默认THUMBNAIL_OUTBOUN)
\Imagine\Image\ManipulatorInterface::THUMBNAIL_OUTBOUN 裁剪模式
\Imagine\Image\ManipulatorInterface::THUMBNAIL_INSET 填充模式
2-2、生成缩略图例子
<?php//生成一张裁剪模式100 x 100 的缩略图 Image::thumbnail('@backend/web/upload/1.jpg', 100 , 100) ->save(Yii::getAlias('@backend/web/upload/1-thumbnail.jpg'), ['quality' => 100]);//生成缩略图的质量 //生成一张填充模式200 x 200 的缩略图 Image::thumbnail('@backend/web/upload/1.jpg', 200 , 200, \Imagine\Image\ManipulatorInterface::THUMBNAIL_INSET) ->save(Yii::getAlias('@backend/web/upload/1-thumbnail-inset.jpg'), ['quality' => 100]);
?>
裁剪图片
3-1、方法及参数说明
\yii\imagine\Image::crop($filename, $width, $height, array $start = [0, 0])//参数说明:
$filename 文件的路径
$width 裁剪的宽度
$height 裁剪的高度
$start 裁剪的x,y 点
3-2、裁剪图片例子
<?php//引用命名空间 use yii\imagine\Image; //裁剪从坐标0,0 裁剪一张300 x 20 的图片,并保存为1-crop.jpg Image::crop('@backend/web/upload/1.jpg', 300 , 20) ->save(Yii::getAlias('@backend/web/upload/1-crop.jpg'), ['quality' => 100]); //裁剪从坐标0,60 裁剪一张300 x 20 的图片,并保存为1-crop-point.jpg Image::crop('@backend/web/upload/1.jpg', 300 , 20, [0, 60]) ->save(Yii::getAlias('@backend/web/upload/1-crop-point.jpg'), ['quality' => 100]);
?>
添加水印
4-1、方法及参数说明:
\yii\imagine\Image::watermark($filename, $watermarkFilename, array $start = [0, 0])//参数说明:
$filename 文件的路径
$watermarkFilename 水印图片
$start 裁剪点(x,y)
4-2、生成水印例子
<?php//在一张图片的0,0 的位置开始打一个水印 $waterFile = '@backend/web/upload/wt.png'; Image::watermark('@backend/web/upload/1.jpg', $waterFile) ->save(Yii::getAlias('@backend/web/upload/1-water.jpg'), ['quality' => 100]); //在一张图片的100,100 的位置开始打一个水印 Image::watermark('@backend/web/upload/1.jpg', $waterFile, [100,100]) ->save(Yii::getAlias('@backend/web/upload/1-water-100-100.jpg'),
['quality' => 100]);
//给图片加文字
$textOpt = ['color'=>'f00','size'=>'40','angle'=>5]; $fontFile = Yii::getAlias('@webroot/font/FZQTJW.ttf'); Image::text(Yii::getAlias('@webroot/img/max.jpg'), '这是一张图片的水印', $fontFile, [300, 450], $textOpt) ->save(Yii::getAlias('@runtime/text-photo.jpg'), ['quality' => 100]);
?>
-
<?php
namespace frontend\controllers;
use yii\web\controller;
use yii;
class DataController extends Controller{public function actionIndex(){ $db = new \yii\db\Connection([ 'dsn' => 'mysql:host=localhost;dbname=aaa', 'username' => 'root', 'password' => '', ]); $db->open(); //查询 $command = $db->createCommand('SELECT * FROM zhuce')->queryAll(); //修改 //$command = $db->createCommand("UPDATE zhuce SET uname='qweqdqdq' WHERE id=2")->execute(); //删除 //$command = $db->createCommand("delete from zhuce where id =2")->execute(); //添加 //$command = $db->createCommand("insert into zhuce (uname,pwd)values('ok','123')")->execute(); //添加多条 //$command = $db->createCommand()->batchInsert('zhuce', ['uname', 'pwd'], [['Tom', 30],['Jane', 20],['Linda', 25]])->execute(); $session = Yii::$app->session; }
}
?>
共 2 条回复 -
图片处理
yii\imagine\Image; //生成一张裁剪模式100 x 100 的缩略图 Image::thumbnail('../web/1.jpg', 100 , 100)->save(Yii::getAlias('../web/2.jpg'),['quality' => 100]); 裁剪从坐标0,0 裁剪一张300 x 20 的图片,并保存为1-crop.jpg Image::crop('../web/1.jpg', 300 , 20,[400,300])->save(Yii::getAlias('../web/1-crop.jpg'), ['quality' => 100]); 给图片加文字 $textOpt = ['color'=>'f00','size'=>'40','angle'=>5]; $fontFile = Yii::getAlias('../web/myweb/fonts/ywyb.ttf'); Image::text(Yii::getAlias('../web/1.jpg'), '呜呼啦嘿', $fontFile, [300, 450], $textOpt)->save(Yii::getAlias('../web/text-1.jpg'), ['quality' => 100]);
-
//视图层
<?phpuse yii\widgets\LinkPager; use yii\helpers\Url; use yii\helpers\Html; use yii\widgets\ActiveForm;
<center><?php $form = ActiveForm::begin([ 'id' => 'login-form', 'options' => ['class' => 'form-horizontal'], 'action' =>'?r=file/sousuo', 'method'=>'get' ]) ?> <?= $form->field($model, 'name')->textInput(['class'=>'dl_textinp','value'=>isset($name) ? $name : ''])->label('标题') ?> <?= $form->field($model, 'content')->textInput(['class'=>'dl_textinp','value'=>isset($content) ? $content : ''])->label('内容') ?> <div class="form-group"> <div class="col-lg-offset-1 col-lg-11"> <?= Html::submitButton('搜索', ['class' => 'btn btn-primary']) ?> </div> </div> <?php ActiveForm::end() ?> <table> <tr> <?php foreach ($list as $key => $val) {?> <td><img src="<?=$val['file']?>" width="150"><br> 标题:<?=$val['name']?><br> 内容:<?=$val['content']?><br> 操作:<a href="">删除</a>//<a href="">修改</a> </td> <?php }?> </tr> </table>
<?php
echo LinkPager::widget(['pagination' => $pagination, 'firstPageLabel'=>"首页", 'prevPageLabel'=>'上一页', 'nextPageLabel'=>'下一页', 'lastPageLabel'=>'尾页',
]);
?>
//控制器
public function actionSousuo(){ $request = Yii::$app->request; $data = $request->get("File"); $where = ' 1=1'; if(!empty($data['name'])){ $where.=" and name like '%".$data['name']."%'"; } if(!empty($data['content'])){ $where.=" and content like '%".$data['content']."%'"; }
$model = new File(); $pagination = new Pagination([ 'defaultPageSize' => 3, 'totalCount' => $model->find()->count(), ]); //print_r($pagination);die; $list = $model->find()->offset($pagination->offset) ->where($where) ->limit($pagination->limit) ->asArray() ->all(); foreach ($list as $key => $val) { $list[$key]['name'] = str_replace($data['name'], '<font color="red">'.$data['name'].'</font>', $val['name']); $list[$key]['content'] = str_replace($data['content'], '<font color="red">'.$data['content'].'</font>', $val['content']); } $url = 'http://www.1507d.com/advanced/frontend/web/index.php?r=apply/apply_download'; $ba = "thunder://".base64_encode("AA".$url."ZZ").""; return $this->render('show', [ 'list' => $list, 'pagination' => $pagination, 'model'=>$model, 'name' => isset($data['name']) ? $data['name'] : '', 'content'=>isset($data['content']) ? $data['content'] : '', 'url'=>$ba, ]); }
//模型层
<?php
namespace frontend\models;//use Yii; use yii\db\ActiveRecord;
class File extends ActiveRecord{
/** * @var UploadedFile */
public $imageFile;
public $verifyCode;
public function scenarios()
{
return [
'sousuo' => [],
'index' => ['verifyCode', 'name','content','imageFile'],
];
}
public function rules(){ return [ ['verifyCode', 'required','message' => '验证码不能为空','on'=>['index']], ['name', 'required','message' => '标题不能为空'], ['content', 'required','message' => '内容不能为空','on'=>['index']], ['verifyCode', 'captcha','on'=>['index']], [['imageFile'], 'file','maxFiles' => 10,'on'=>['index']], [['imageFile'], 'required','message' => '文件不能为空','on'=>['index']], ]; }
}
?>共 3 条回复public function actionXiazai()
{ $url = 'http://www.1507d.com/advanceds/frontend/web/index.php?r=file/sousuo'; $content = file_get_contents($url); $date=date("Ymd-H:i:m"); $filename = 'aa.html'; file_put_contents($filename, $content); Header( "Content-type: application/octet-stream "); Header( "Accept-Ranges: bytes "); Header( "Accept-Length: " .filesize($filename)); header( "Content-Disposition: attachment; filename= {$date}.doc"); readfile($filename); //迅雷下载 // $url = 'http://www.1507d.com/advanced/frontend/web/index.php?r=apply/apply_download'; // $ba = "thunder://".base64_encode("AA".$url."ZZ").""; }
@小__刚 //排序
function getComment($data,$id=0,$static=0) { if(empty($data)) return $data; $arr = array(); foreach ($data as $key => $val) { if($val['parent_id'] == $id){ $va['son'] = $static; $arr[] = $val; $arr = array_merge($arr,$this->getComment($data,$val['id'],$static+1)); } } return $arr; }
-
三级联动
<?= $form->field($region,'province')->label('省')->dropDownList($region->getCityList(0), [ 'prompt'=>'--请选择省--', 'onchange'=>' $(".field-region-city").hide(); $(".field-region-area").hide(); $.post("'.yii::$app->urlManager->createUrl('resume/site').'&level=1&parent_id="+$(this).val(),function(data){ $(".field-region-city").show(); $("#region-city").html(data); });', ]) ?> <?= $form->field($region, 'city')->label('市')->dropDownList($region->getCityList($region->province), [ 'prompt'=>'--请选择市--', 'onchange'=>' $(".field-region-area").show(); $.post("'.yii::$app->urlManager->createUrl('resume/site').'&level=2&parent_id="+$(this).val(),function(data){ $("#region-area").html(data); });', ]) ?> <?= $form->field($region, 'area')->label('区')->dropDownList($region->getCityList($region->city),['prompt'=>'--请选择区--',]) ?>
林小陌 上海
最后登录:2017-11-13
在线时长:2小时59分
- 粉丝7
- 金钱75
- 威望10
- 积分195