// 新建文件 A.php<?phpnamespacea\b\c;classApple{functioninfo(){echo'this is Apple A';}}// 新建文件 B.php<?phpnamespaced\e\f;classApple{functioninfo(){echo'this is Apple B';}}// 新建文件 C.php<?php// 不存在於任何命名空間:全局類classApple{functioninfo(){echo'this is Apple C';}}// 新建文件 index.php<?phprequire_once('A.php');require_once('B.php');require_once('C.php');// use 關鍵字:一旦使用 Apple() 類,默認使用 a\b\c 下的 Apple()usea\b\c\Apple;// as 關鍵字:重命名類名used\e\f\Appleas bApple;// $a_app = new a\b\c\Apple();$a_app=newApple();$a_app2=newApple();$a_app->info();$b_app=newbApple();// 訪問全局類$c_app=new\Apple();
<?phpnamespaceapp\models;useyii\db\ActiveRecord;// 創建數據模型,對數據庫 Test 進行操作classTestextendsActiveRecord{// 設定表名(如果表名和類名不一致)publicstaticfunctiontableName(){return'test';}publicfunctionrules(){// 驗證器參考:https://www.yiichina.com/doc/guide/2.0/tutorial-core-validatorsreturn[['id','integer'],['title','string','length'=>[0,10]]];}}
創建 basic/controllers/TestController.php
<?phpnamespaceapp\controllers;useYii;useyii\web\Controller;useapp\models\Test;// 加載 modelclassTestControllerextendscontroller{publicfunctionactionIndex(){// 1. 單表查詢// 查詢數據,同時防止 SQL 注入$id='1 or 1=1';$sql="SELECT * FROM test WHERE id = :id";$results= Test::findBySql($sql,[':id'=>$id])->all();// 返回一個數組,數組裏面是 id = 1 的對象// id = 1;$results= Test::find()->where(['id'=>1])->all();// id > 0;$results= Test::find()->where(['>','id',0])->all();// id >= 1 AND id <= 2$results= Test::find()->where(['between','id',1,2])->all();// title like "%title1%"$results= Test::find()->where(['like','title','title1'])->all();// 更多 where 方法參考:https://www.yiichina.com/doc/api/2.0/yii-db-queryinterface#where()-detail// 對象在內存裏的佔用量比數組高,所以要優化// 查詢結果轉化爲數組$results= Test::find()->where(['like','title','title1'])->asArray()->all();// 批量查詢foreach(Test::find()->asArray()->batch(1)as$tests){print_R($tests);}// 另: createCommand() 查詢// $sql = "SELECT * FROM test WHERE id = " . $id;// $results = Yii::$app->db->createCommand($sql)->queryAll();// 2. 單表刪除:調用對象 delete() 方法$results= Test::find()->where(['id'=>1])->all();$results[0]->delete();// 刪除條件
Test::deleteAll('id>:id',[':id'=>0]);echo'<pre>';print_R($results);// 3. 單表添加數據$test=newTest;$test->title='title4';// 調用 model 設置的驗證器$test->validate();if($test->hasErrors()){echo$test->getErrors();
exit;}// $test->save();// 4. 單表數據修改$test= Test::find()->where(['id'=>3])->one();//print_r($test);$test->title='title33';$test->save();}}