在終端執行 mysql -u root –p
登入資料後,通過執行 CREATE DATABASE mystudy CHARACTER SET utf8 COLLATE utf8_general_ci; 建立一個新的資料庫;
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host = localhost;dbname = mystudy', 'username' => 'root', 'password' => '', 'charset' => 'utf8', ]; ?>
第3步 - 在專案根檔案夾執行:yii migrate/create test_table 。此命令將用於建立管理資料庫資料庫遷移。 migrations檔案會出現在專案的根的 migrations 檔案夾中。
<?php use yii\db\Schema; use yii\db\Migration; class m160529_014611_test_table extends Migration { public function up() { $this->createTable("user", [ "id" => Schema::TYPE_PK, "name" => Schema::TYPE_STRING, "email" => Schema::TYPE_STRING, ]); $this->batchInsert("user", ["name", "email"], [ ["User1", "[email protected]"], ["User2", "[email protected]"], ["User3", "[email protected]"], ["User4", "[email protected]"], ["User5", "[email protected]"], ["User6", "[email protected]"], ["User7", "[email protected]"], ["User8", "[email protected]"], ["User9", "[email protected]"], ["User10", "[email protected]"], ["User11", "[email protected]"], ]); } public function down() { //$this->dropTable('user'); } } ?>
第6步-現在,我們需要為user表建立模型。為了簡便起見,我們將使用GII程式碼生成工具。在瀏覽器中開啟 url: http://localhost:8080/index.php?r=gii 。
然後,點選 「Model generator」 下的 「Start」按鈕。 填寫表名(「user」)和模型類(「MyUser」),單擊「Preview」按鈕,最後點選 「Generate」 按鈕。
public function actionDataWidget() { $model = MyUser::find()->one(); return $this->render('datawidget', [ 'model' => $model ]); }
<?php use yii\widgets\DetailView; echo DetailView::widget([ 'model' => $model, 'attributes' => [ 'id', //formatted as html 'name:html', [ 'label' => 'e-mail', 'value' => $model->email, ], ], ]); ?>