




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領
文檔簡介
第YII框架常用技巧總結(jié)本文實例總結(jié)了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查詢并緩存結(jié)果
$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關(guān)閉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);
關(guān)于事務:
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)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年心理發(fā)展與教育技術(shù)考試試卷及答案
- 2025年國際貿(mào)易與經(jīng)濟學考研試卷及答案分析
- 2025年全國高中數(shù)學競賽試卷及答案
- 2025年人力資源管理考試題及答案
- 海外城市綜合體施工進度監(jiān)理及技術(shù)支持合同
- 商標品牌授權(quán)運營及市場拓展協(xié)議
- 電子商務平臺技術(shù)研發(fā)與業(yè)務模式創(chuàng)新協(xié)議
- 基因治療項目臨床試驗研究員派遣合同
- 果園無人機植保租賃與智能植保解決方案協(xié)議
- 網(wǎng)紅蛋糕店區(qū)域代理加盟連鎖經(jīng)營合同
- GB/T 18760-2025消費品售后服務方法與要求
- 中職教案評比評價表
- 四年級語文下冊 第六單元 語文園地第1課時說課稿 新人教版
- 國內(nèi)外引信彈道炸事故及其原因綜述
- 小學高年級學生身體滿意度和人際關(guān)系困擾的關(guān)系及自尊的中介作用
- 醫(yī)院保密知識培訓課件
- 標準化基礎知識培訓課件
- 第4章我們生活的大地知識點清單-2024-2025學年浙教版七年級下冊科學
- 軍事通信基礎知識
- 建筑工地挖掘機吊裝施工方案
- 8.2 法治政府 課件-高中政治統(tǒng)編版必修三政治與法治
評論
0/150
提交評論