Yii 學習筆記

Yii經常使用執行SQL方法
======================================================
======================================================
//執行SQL:createCommand
query();    //select
queryAll();
queryRow();
queryScalar();
execute();    //delete insert update 

//舉例
$sql = "SELECT LEFT(region_code,2) as provinceid,region_name";
$sql .= " FROM `dim_luna_region`";
$sql .= " GROUP BY provinceid ORDER BY region_code asc";
$provinces = Yii::app()->db->createCommand($sql)->queryAll();
//舉例
Yii::app()->db->createCommand()
    ->select('name, started_date, finished_date')
    ->from('customer c')
    ->leftJoin('accounting a', 'c.id=a.customerid')
    ->rightJoin('customer_employee ce', 'c.id=ce.customerid')
    ->join('app_info_list il', 'dl.AppId = il.Id')
    ->where('ce.employeeid=:id', array(':id'=>2))
    ->group('AppId')
    ->order('value desc')
    ->limit(10)
    ->queryRow();
//舉例
$command = Yii::app()->db->createCommand();
$command->select('count(Id) as countApp, sum(Up) as totalUp');
$command->from('app_info_list');
$command->where('CommitUserId = :CommitUserId', array(':CommitUserId' => $memberID));
$result = $command->queryRow();
//舉例???
$userId = Yii::app()->db->createCommand($selectSql)->queryScalar();
//舉例???
Yii::app()->db->createCommand($updateSql)->execute();

//執行SQL:CDbCriteria
//舉例
$criteria = new CDbCriteria;
$criteria->alias = 'a';
$criteria->select    = 'name, started_date, finished_date';
$criteria->join      = 'RIGHT JOIN customer_employee ON customer.id=customer_employee.customerid ';
$criteria->join     .= 'LEFT JOIN accounting ON customer.id=accounting.customerid';
$criteria->group = ' GROUP BY a.PushId';
$criteria->condition = 'customer_employee.employeeid=:id';
$criteria->params    = array(':id'=>2);
$customers = Customers::model()->find($criteria);
 

//執行SQL:model
find();
findAll();
findByPk();
findAllByAttributes();
count();
delete();
deleteAll();

//舉例
$news = AppDownloadLog::model()->find('Hash = :hash', array(':hash' => $hash));
if (! $news instanceof AppDownloadLog) {
    throw new THttpException('文章ID有誤');
}
//舉例
$models = AppInfoList::model()->findAll();
//舉例
$yesterdayApps = AppInfoList::model()->findAll('CommitTime > "' . $yesterday . '" and CommitTime < "' . $today . '" and Status = 0');
//舉例
$models_user = User::model()->findAllByAttributes(array('Status' => '-1'));
//舉例
AppInfoList::model()->findByPk($id);
//舉例
User::model()->count( "Status = 0 and CreateTime < '$yesterday' and LastLoginTime>='$yesterday'" );
//舉例
$commentModel = AppPushListReviews::model()->findAll(
    array(
        'select' => array('Id', 'Sort', 'Up'),    //可選,默認所有
        'distinct'  => true,        //可選
        'condition' => 'Status=0 and Used=0 and PushId=:PushId and Content !=""',
        'params' => array(':PushId'=>$pushId),
        'order' => 'Id desc',    //'order' => new CDbExpression('RAND()'),
        'limit' => 1
    )
);
//舉例
 AppPushListDetail::model()->find('PushId=' . $row)->delete();
//舉例
$deleteChildrenReplyNum = AppReviews::model()->deleteAll('Pid=:pid', array(':pid' => $reply->Id));
//擴展舉例 published
$product = CoinExchangeProduct::model()->published()->findByPk($productID);
public function scopes()
{
    return array(
        'published' => array(
            'condition' => 'status = 0'
        )
    );
}
//擴展舉例 together
AppReviews::model()->with('author_icon')->together()->findAll(
    array(
        'select'=> array('Id', 'Pid', 'Content', 'UpdateTime', 'AuthorId', 'ToAuthorId'),
        'order' => 't.Pid asc, t.UpdateTime desc',
        'condition' => 'AppId = :AppId',
        'params' => array(':AppId' => $appID)
    )
);



adp代碼學習
======================================================
======================================================
多語言。加載messages/[module]
Yii::t($this->getModule()->ID, $this->ID . '_' . $field)

權限控制
components/controller.php  function filters(){}
components/WebUser.php $this->perm;登陸的時候存入的

權限設置數據表
module_adm



Yii框架設置
======================================================
======================================================
//打開gii工具
後臺打開 protected/config/main.php  搜索gii
訪問gii http://localhost/shop/index.php?r=模塊名字(gii)

//建立模塊成功配置
位置:protectd/config/main.php
'modules'=>array(
    'admin'    // 模塊名稱
),

//默認控制器    
前臺默認控制器:SiteController.php
後臺默認控制器:DefaultController.php
    
//controller位置 
protected/components

//定義常量位置 
protected/assets/default
引入已經定義好的系統常量 index.php
require_once(dirname(__FILE__).'/protected/config/constant.php');

//數據庫
數據庫配置:protected/config/database.php
注意:php.ini 開啓擴展 
    extension=php_pdo_mysql.dll         
    extension=php_mysql.dll
檢測是否鏈接上數據庫:var_dump(Yii::app()->db);

framework/web/CWebApplication.php
framework/base/CApplication.php
famework/YiiBase.php
framework/db/CDbConnection.php

//所有代碼
yii有10000行,所有在framework/yiilite.php 有體現

//表單小物件
$form = $this -> beginWidget('CActiveForm'); 

  
//form submit
註冊:
給模型收集表單信息
foreach($_POST['User'] as $_k => $_v){
    $user_model -> $_k = $_v;
}

//上邊的foreach,在yii框架裏邊有優化,使用模型屬性attributes來進行優化
//attributes 屬性已經把foreach集成好了,咱們能夠直接使用
$user_model -> attributes = $_POST['User'];
        
input radio:(yiilist.php)
<?php echo $form->radioButtonList($user_model,'user_sex',$sex,array('separator'=>'&nbsp;')); ?>
input select:
<?php echo $form -> dropDownList($user_model,'user_xueli',$xueli); ?>
input checkbox:
<?php echo $form -> checkBoxList($user_model,'user_hobby',$hobby,array('separator'=>'&nbsp;')); ?>
表單顯示錯誤信息:
<?php echo $form->textField($user_model,'username',array('class'=>'inputBg','id'=>'User_username')); ?>
<!--表單驗證失敗顯示錯誤信息-->
<?php echo $form ->error($user_model,'username'); ?>
        
//驗證:
framework/validators/cValidator.php
舉例:
    array('username','required','message'=>'用戶名必填'),
    //用戶名不能重複(與數據庫比較)
    array('username', 'unique', 'message'=>'用戶名已經佔用'),
    array('password','required','message'=>'密碼必填'),
    //驗證確認密碼password2  要與密碼的信息一致
    array('password2','compare','compareAttribute'=>'password','message'=>'兩次密碼必須一致'),
    //郵箱默認不能爲空
    array('user_email','email','allowEmpty'=>false,  'message'=>'郵箱格式不正確'),
    //驗證qq號碼(都是數字組成,5到12位之間,開始爲非0信息,使用正則表達式驗證)
    array('user_qq','match','pattern'=>'/^[1-9]\d{4,11}$/','message'=>'qq格式不正確'),
    //驗證手機號碼(都是數字,13開始,一共有11位)
    array('user_tel','match','pattern'=>'/^1[3,4,5,6,7,8]{1}\d{9}$/','message'=>'手機號碼格式不正確'),
    //驗證學歷(信息在二、三、四、5之間則表示有選擇,不然沒有),1正則;2範圍限制
    //範圍限制
    array('user_xueli','in','range'=>array(2,3,4,5),'message'=>'學歷必須選擇'),
    //驗證愛好:必選兩項以上(自定義方法對愛好進行驗證)
    array('user_hobby','check_hobby'),
    //爲沒有具體驗證規則的屬性,設置安全的驗證規則,不然attributes不給接收信息
    array('user_sex,user_introduce','safe'),

    
Yii調試
======================================================
======================================================
//讓mysql拋出異常信息(js裏面也是能夠看到的)
new CDbExpression($sql);

//網站底部顯示日誌信息
位置:protectd/config/main.php
搜索:CWebLogRoute
array(
    'class'=>'CWebLogRoute',
),


Yii經常使用內置方法:
======================================================
======================================================
//獲取當前Yii版本
Yii::getVersion();

//獲取當前域名
Yii::app()->request->hostInfo

//在控制器中獲取控制器名:
$this->id;
$this->ID;
$name = $this->getId();  
//在控制器beforeAction()回調函數中獲取動做名
$name = $action->id;  
//在控制器中獲取modules名:
$this->getModule()->ID
//控制器中獲取表名
$model->table;
//在視圖中獲取控制器名:
$name = Yii::app()->controller->id;  
//在其餘地方獲取動做名:
$name = $this->getAction()->getId();  
//在模型中獲取
$this->getModule()->id
$this->Module->getId()


Yii控制器
======================================================
======================================================
//獲取字段屬性
$model_new_creative = new LunaCreative();
$attrs = $model_new_creative->attributeNames();

//驗證網址
if(!Func::validateIsUseful($model->website)){
    throw new THttpException('網址不可用!');
}



Yii定時任務
======================================================
======================================================
準備階段:
    要定時執行的PHP程序存放位置:trunk/protected/commands/***.php
執行階段:
    打開cmd,進入到相應目錄,敲入命令yiic,便可看到所定製的任務計劃
        例如:D:\wamp\www\appgrub\trunk\protected>yiic
    執行對應的文件
        例如:D:\wamp\www\appgrub\trunk\protected>yiic report
    此時已經默認執行了ReportCommand.php中的actionIndex()方法
    若是要執行控制裏面的其餘方法actionshow()方法
        例如:D:\wamp\www\appgrub\trunk\protected>yiic report show
    若是要執行控制裏面的其餘方法actionshow($p1,$p2)方法
        例如:D:\wamp\www\appgrub\trunk\protected>yiic report show  --p1=*** --p2=***
執行成功
    

Yii Session
======================================================
======================================================
設置:Yii::app()->session['var']='value';
使用:Yii::app()->session['var'];
移除: unset(Yii::app()->session['var']);

最後,當用戶退出登陸(logout),你須要消除痕跡,可以使用:
Yii::app()->session->clear() 移去全部session變量,而後,調用
Yii::app()->session->destroy() 移去存儲在服務器端的數據。
相關文章
相關標籤/搜索