




版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
第YII框架常用技巧總結本文實例總結了YII框架常用技巧。分享給大家供大家參考,具體如下:
獲取當前Controllername和actionname(在控制器里面使用)
echo$this-
echo$this-action-
控制器獲取當前模塊
$this-module-id
不生成label標簽
//ActiveForm類
$form-field($model,'字段名')-passwordInput(['maxlength'=true])-label(false)
Yii2獲取接口傳過來的JSON數(shù)據(jù):
Yii::$app-request-rawBody;
防止SQL和Script注入:
useyii\helpers\Html;
useyii\helpers\HtmlPurifier;
echoHtml::encode($view_hello_str)//可以原樣顯示script/script代碼
echoHtmlPurifier::process($view_hello_str)//可以過濾掉script/script代碼
大于、小于條件查詢
//SELECT*FROM`order`WHERE`subtotal`200ORDERBY`id`
$orders=$customer-getOrders()
-where(['','subtotal',200])
-orderBy('id')
-all();
搜索的時候添加條件篩選
$dataProvider=$searchModel-search(Yii::$app-request-queryParams);
//$dataProvider-query-andWhere(['pid'=0]);
$dataProvider-query-andWhere(['','pid',0]);
//可選傳參
$dataProvider-query-andFilterWhere(['id'=isset($id)$id:null]);
有兩種方式獲取查詢出來的name為數(shù)組的集合[name1,name2,name3]:
方式一:
return\yii\helpers\ArrayHelper::getColumn(User::find()-all(),'name');
方式二:
returnUser::find()-select('name')-asArray()-column();
打印數(shù)據(jù):
//引用命名空間
useyii\helpers\VarDumper;
//使用
VarDumper::dump($var);
//使用2第二個參數(shù)是數(shù)組的深度第三個參數(shù)是是否顯示代碼高亮(默認不顯示)
VarDumper::dump($var,10,true);die;
表單驗證,只要需要一個參數(shù):
publicfunctionrules()
return[
[['card_id','card_code'],function($attribute,$param){//至少要一個
if(empty($this-card_code)empty($this-card_id)){
$this-addError($attribute,'card_id/card_code至少要填一個');
},'skipOnEmpty'=false],
SQLisnotnull條件查詢
//['not'=['attribute'=null]]
//['ISNULL(`attribute`)'=true]
$query=newQuery;
$query-select('ID,City,State,StudentName')
-from('student')
-where(['IsActive'=1])
-andWhere(['not',['City'=null]])
-andWhere(['not',['State'=null]])
-orderBy(['rand()'=SORT_DESC])
-limit(10);
校驗point_template_id在PointTemplate是否存在
publicfunctionrules()
return[
[['point_template_id'],'exist',
'targetClass'=PointTemplate::className(),
'targetAttribute'='id',
'message'='此{attribute}不存在。'
Yii給必填項加星
div.requiredlabel:after{
content:
"*";
color:
red;
執(zhí)行SQL查詢并緩存結果
$styleId=Yii::$app-request-get('style');
$collection=Yii::$app-db-cache(function($db)use($styleId){
returnCollection::findOne(['style_id'=$styleId]);
},self::SECONDS_IN_MINITUE*10);
場景:
數(shù)據(jù)庫有user表有個avatar_path字段用來保存用戶頭像路徑
需求:頭像url需要通過域名/作為基本url
目標:提高代碼復用
此處/可以做成一個配置
示例:
User.php
classUserextends\yii\db\ActiveRecord
publicfunctionextraFields()
$fields=parent::extraFields();
$fields['avatar_url']=function(){
returnempty($this-avatar_path)'可以設置一個默認的頭像地址':'/'.$this-avatar_path;
return$fields;
ExampleController.php
classExampleControllerextends\yii\web\Controller
publicfunctionactionIndex()
$userModel=User::find()-one();
$userData=$userModel-toArray([],['avatar_url']);
echo$userData['avatar_url'];//輸出內(nèi)容:/頭像路徑
Model里面rules聯(lián)合唯一規(guī)則
復制代碼代碼如下:[['store_id','member_name'],'unique','targetAttribute'=['store_id','member_name'],'message'='ThecombinationofStoreIDandMemberNamehasalreadybeentaken.'],
Model多個字段一條規(guī)則不同提示
[['name','email','subject','body'],'required','message'='{attribute}必須'],
標量查詢
Post::find()-select('title')-where(['user_id'=$userId])-scalar();
生成SQL:
SELECT`title`FROM`post`WHERE`user_id`=1
直接輸出title的值。
如果select('title')不寫的話,生成SQL是:
`SELECT*FROM`post`WHERE`user_id`=1`
直接輸出id的值
表單驗證,去除首尾空格:
publicfunctionrules()
return[[title','content'],'trim']];
單獨為某個Action關閉Csrf驗證
新建一個Behavior
useYii;
useyii\base\Behavior;
useyii\web\Controller;
classNoCsrfextendsBehavior
public$actions=[];
public$controller;
publicfunctionevents()
return[Controller::EVENT_BEFORE_ACTION='beforeAction'];
publicfunctionbeforeAction($event)
$action=$event-action-
if(in_array($action,$this-actions)){
$this-controller-enableCsrfValidation=false;
然后在Controller中添加Behavior
publicfunctionbehaviors()
return[
'csrf'=[
'class'=NoCsrf::className(),
'controller'=$this,
'actions'=[
'action-name'
LIKE查詢單邊加%
['like','name','tester']會生成nameLIKE'%tester%'。
['like','name','%tester',false]=nameLIKE'%tester'
$query=User::find()-where(['LIKE','name',$id.'%',false]);
SQL隨機抽取十名幸運用戶
$query=newQuery;
$query-select('ID,City,State,StudentName')
-from('student')
-where(['IsActive'=1])
-andWhere(['not',['State'=null]])
-orderBy(['rand()'=SORT_DESC])
-limit(10);
關于事務:
Yii::$app-db-transaction(function(){
$order=newOrder($customer);
$order-save();
$order-addItems($items);
//這相當于下列冗長的代碼:
$transaction=Yii::$app-db-beginTransaction();
try{
$order=newOrder($customer);
$order-save();
$order-addItems($items);
$transaction-commit();
}catch(\Exception$e){
$transaction-rollBack();
throw$e;
批量插入數(shù)據(jù)
第一種方法
$model=newUser();
foreach($dataas$attributes){
$_model=clone$model;
$_model-setAttributes($attributes);
$_model-save();
第二種方法
$model=newUser();
foreach($dataas$attributes){
$model-isNewRecord=true;
$model-setAttributes($attributes);
$model-save()$model-id=0;
URL操作
獲取url中的host信息
Yii::$app-request-getHostInfo()
獲取url中的路徑信息(不包含host和參數(shù)):
Yii::$app-request-getPathInfo()
獲取不
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2026屆山西省汾西縣中考語文模擬試題含解析
- 現(xiàn)代教育技術教學設計概述
- 膝關節(jié)CT檢查技術
- 招生工作匯報體系構建路徑
- 二零二五年度綠色建筑綠色建筑節(jié)能檢測勞務合同規(guī)范模板
- 二零二五年專業(yè)考察團包車協(xié)議書
- 二零二五版網(wǎng)絡短視頻剪輯師招聘合同范本
- 2025-2030中國彩色偏光片市場現(xiàn)狀調(diào)查與投資價值評估報告
- 二零二五年度黃金抵押貸款業(yè)務合同模板大全
- 2025版公寓式酒店委托管理及安全防范服務協(xié)議
- 瞼板腺按摩治療講課件
- 旅游六要素講課件
- 等邊三角形-第2課時含30^°角的直角三角形的性質課件人教版數(shù)學八年級上冊
- 高級駕駛員試題及答案
- 實驗室5s管理制度
- 2024電力檢修工程預算定額使用指南
- 干事考試試題及答案
- 2025呂梁學院教師招聘考試試題
- 初創(chuàng)科技公司管理制度
- 借道施工安全協(xié)議書
- 火災應急預案評審結論(3篇)
評論
0/150
提交評論