在終端執行 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」 按鈕。
<?php namespace app\models; use Yii; /** * This is the model class for table "user". * * @property integer $id * @property string $name * @property string $email */ class MyUser extends \yii\db\ActiveRecord { const EVENT_NEW_USER = 'new-user'; public function init() { // first parameter is the name of the event and second is the handler. $this->on(self::EVENT_NEW_USER, [$this, 'sendMailToAdmin']); } /** * @inheritdoc */ public static function tableName() { return 'user'; } /** * @inheritdoc */ public function rules() { return [ [['name', 'email'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'name' => 'Name', 'email' => 'Email', ]; } public function sendMailToAdmin($event) { echo 'mail sent to admin using the event'; } } ?>
public function actionTestEvent() { $model = new MyUser(); $model->name = "John"; $model->email = "[email protected]"; if($model->save()) { $model->trigger(MyUser::EVENT_NEW_USER); } }