本文實例講述了yii2中使用Active Record模式的方法。分享給大家供大家參考,具體如下:
1. 在db.php中配置相應的數據庫信息:
1
2
3
4
5
6
7
|
return [ 'class' => 'yii\db\Connection' , 'dsn' => 'mysql:host=localhost;dbname=yii2basic' , 'username' => 'root' , 'password' => '' , 'charset' => 'utf8' , ]; |
2. 使用gii模塊來自動生成相應的代碼(訪問鏈接http://localhost/basic/web/index.php?r=gii):
利用ModelGenerator 和CURD Generator 來自動生成相應的模型代碼和增刪改查的代碼
3. 當數據庫中的表需要進行修改時可以使用migration:
在項目中執行命令:./yii migrate/create “自己定義名稱”
在項目中會生成一個新的文件夾migrations,打開文件夾中的文件:
1
2
3
4
5
6
7
8
9
10
11
12
|
class m150225_022640_modify_book_table extends Migration { public function up() { $this ->addColumn( "book" , "book_desc" , yii\db\mssql\Schema::TYPE_TEXT); } public function down() { echo "m150225_022640_modify_book_table cannot be reverted.\n" ; return false; } } |
在命令行中使用命令 :./yii migrate 即可執行腳本中的up函數
在命令行中使用命令: ./yii migrate/down 即可執行腳本中的down函數
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。