ThinkPHP5 usage history

1. Search for plugins in the drop-down box and update the content asynchronously

  • When using the tp5 template, the built-in chosen.jquery.js plug-in can enable the drop-down box to have a search function.
    However, when using ajax to update select asynchronously, the content of select changes, and the content of the drop-down box element generated by the chosen plugin does not change. It needs to be processed separately. The code is as follows

    <label class="col-sm-3 control-label">用户类型:</label>
     <div class="input-group col-sm-4">
         <select class="form-control m-b " name="type" id="type">
             <option value="1">普通用户</option>
         </select>
     </div>

     <label class="col-sm-3 control-label">所属公司:</label>
     <div class="input-group col-sm-4">
         <select class="form-control m-b" name="company_id" id="company_id">
             <option value="0">公司列表</option>
         </select>
     </div>
<script>
	$('#type').change(function(){
     
     
        var type = $(this).val();
        $.get('/companys/type/'+ type,function(data){
     
     
            $('#company_id').html(data);//ajax获取公司的option字符串并更新
            $("#company_id").trigger("chosen:updated");//更新chosen生成的元素
        },)
    });
</script>

2. Model usage issues

① Union table query

When using the model to query the table, all the filter conditions used and the fields to be queried must be added with the table name (or alias) before the field, otherwise various exceptions will appear later

② Reuse of model

When you need to use the same model for multiple operations, if a model performs a select() operation, the query conditions such as where and join loaded before the model will be cleared, and then the model will be used for the select() operation , The previously loaded condition will not be executed. When we encounter multiple operations that need to use selec query, you can use it before selectclone Clone a new model object for the execution of an operation select.

3. In Db::name(), after group grouping is used, count() cannot be used to aggregate query later

4. Exception handling of wrong request address

  • 1. Illegal operation request

When requesting a method that does not exist in the controller, the following error will be reported. For
Insert picture description here
this situation, TP has a specific method to handle it. You only need to define a method named _empty in the controller. When requesting a method that does not exist, it will automatically Call the _empty method.

  • 2. Illegal controller request

When the requested controller does not exist, the following error will be reported.
Insert picture description here
TP also provides a solution for this situation. In the default configuration, there are the following configurations.
Insert picture description here
As long as the Error controller class is implemented under the corresponding module, and the index method is established, when a controller that does not exist is requested, the index method under Error will be automatically called

  • 3. Illegal module request

When the requested module does not exist, the following error will be reported.
Insert picture description here
In response to this situation, TP has not specifically set a solution. But we can modify the App.php file according to the above two situations.
Insert picture description here
The code in the following box is newly added by me, which means that when the module does not exist, we customize a module and let the program go to this module to find the corresponding The name of the controller and method. Note here that the custom module name must not be usederror, There will be an inexplicable problem.
After modifying the APP.php file, go to application to create a new module and controller, as follows
Insert picture description here

5. The api interface returns status

  • When using tp to write the interface, we can specify the status code and information for some expected conditions, but sometimes it is some abnormality of the program, we can not make all judgments. You can use the system's built-in error handling mechanism to return the system catch exceptions in the same format as the interface. Modifythinkphp/library/think/exception/Handle.phpFile as follows
    Insert picture description here

6. Multi-condition query of where array conditions

  • We generally use the form:$where = [‘id’=>1,‘status’=>2] This kind of array is used as a condition and placed in where ($where) as a query condition. This is more convenient for expansion. Summarize several commonly used where multi-condition query methods
//in条件
$where['id'] = ['in',[1,3,4,5]];
//范围查询
$where['id'] = ['between',[11,22]];
//时间范围查询,当字段类型为date,不能无法使用常规的范围查询
$where['date'] = [
	['>=','2020-0505'],
	['<=','2020-05-30'],
	'and'
];

7. The controller gets the binding parameters

For example: public function index ($page){}
can automatically obtain the parameter named page passed by get or post.
I always thought that when I wrote it like this, I can only get the parameters passed through the url

8. Limit query

Db::name(‘table’)->limit(5,10)->select();

Db::name(‘table’)->limit(‘5,10’)->select(); The
effect is the same, starting from position 5 and taking 10 pieces of data

9. PHPexcel import and export

Import

			//获取上传表单选中的文件信息
			$file = request()->file('file');
        	$info =$file->getInfo();
        	if(!is_file($info['tmp_name']))	return '文件不存在';
			//开始上传
            \think\Loader::import('.PHPExcel.PHPExcel.IOFactory');
            $objReader =  new \PHPExcel_Reader_Excel2007();
            if( ! $objReader->canRead($file)) {
    
    
                $objReader = new \PHPExcel_Reader_Excel5();
                if(!$objReader->canRead($file)) {
    
    
                    return json(['code' => 0, 'data' => '', 'msg' => '仅支持 .xls 类型的文件']);
                }
            }
            $objPHPExcel = $objReader->load($file,$encode='utf-8');//加载文件
			
            $sheet = $objPHPExcel->getSheet(1);//取得sheet表
			$objPHPExcel->setActiveSheetIndex(1);
            $highestRow = $sheet->getHighestRow(); // 取得总行数
			
			//echo $highestRow;exit;
            $aa=[];
			$salary_arr = Db::name('un_major_salary')->order('salary asc')->column('code');
            for($i=3;$i<=$highestRow;$i++)
            {
    
    
				$data=[];
                $data['is_red'] = $objPHPExcel->getActiveSheet()->getCell("C".$i)->getValue()??0;
				$data['is_yellow'] = $objPHPExcel->getActiveSheet()->getCell("D".$i)->getValue()??0;
                $data['is_green'] = $objPHPExcel->getActiveSheet()->getCell("E".$i)->getValue()??0;
				
				Db::name('university_major')->where('major_code',$code)->update($data);
            }

Export

            $data = collection($company->select())->toArray();

            \think\Loader::import('.PHPExcel.PHPExcel.IOFactory');
            $obj =  new \PHPExcel();
            $fileName = $title;
            $fileType = "xlsx";
            // 设置当前sheet
            $obj->setActiveSheetIndex(0);
            // 设置当前sheet的名称
            $obj->getActiveSheet()->setTitle('list');
            // 列标
            $list = ['A', 'B', 'C','D','E'];
            // 填充第一行数据
            $title_E = $type == 1 || $type == 2?'最后清洗时间':'最后检测时间';
            $obj->getActiveSheet()
                ->setCellValue($list[0] . '1', '商户名称')
                ->setCellValue($list[1] . '1', '联系人')
                ->setCellValue($list[2] . '1', '联系电话')
                ->setCellValue($list[3] . '1', '地址')
                ->setCellValue($list[4] . '1', $title_E);

            foreach($data as $i=>$v){
    
    
                $obj->getActiveSheet()->setCellValue($list[0] . ($i + 2), $v['name']);//将其设置为文本格式
                $obj->getActiveSheet()->setCellValue($list[1] . ($i + 2), $v['contacts']);
                $obj->getActiveSheet()->setCellValue($list[2] . ($i + 2), $v['phone'], \PHPExcel_Cell_DataType::TYPE_STRING);
                $obj->getActiveSheet()->setCellValue($list[3] . ($i + 2), $v['base_address'].$v['address']);
                $obj->getActiveSheet()->setCellValue($list[4] . ($i + 2), $v['last_date']);
            }
            // 设置列宽
            $obj->getActiveSheet()->getColumnDimension('A')->setWidth(20);
            $obj->getActiveSheet()->getColumnDimension('B')->setWidth(20);
            $obj->getActiveSheet()->getColumnDimension('C')->setWidth(20);
            $obj->getActiveSheet()->getColumnDimension('D')->setWidth(80);
            $obj->getActiveSheet()->getColumnDimension('E')->setWidth(20);

            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '.xlsx');
            header('Cache-Control: max-age=1');
            $objWriter = \IOFactory::createWriter($obj, 'Excel2007');
            //输出内容之前要先清理缓冲区,否则可能会出现下载的文件打不开的现象
            ob_end_clean();
            $objWriter->save('php://output');
            exit;

Guess you like

Origin blog.csdn.net/u012830303/article/details/105712246