:::

6-1 編輯並執行測驗(exam)的 migrate 檔案

建立一個隨機題庫,並能進行測驗,會用到許多表。為了減低複雜程度,我們暫時先做一下限制:

  1. 教師可以建立許多測驗
  2. 每一個測驗,可以有N個題目,從中隨機抽出M筆題目來考試
  3. 僅學生可以進行測驗

一、編輯測驗 migrate 檔案

  1. migrate 檔案就是用來定義資料表欄位的檔案,屆時可用指令自動建立(或增減)資料表欄位

    • 先確定 /專案/.env 中的資料庫設定有設定正確

    • 確定有啟動MySQL資料庫,並確定已經建立 DB_DATABASE 定義的資料庫

  2. 確認有無 /專案/database/migrations/日期_create_exams_table.php(上一節有做了),若是還沒有上述檔案(或者是只要建立資料表,但不需要建立Model的時候),執行以下語法會自動生出 migrate 檔案(其中,是create_exams_table檔案名稱,--create=exams則是資料表名稱,慣例為複數):

    php artisan make:migration create_exams_table --create=exams
  3. 編輯 /專案/database/migrations/日期_create_exams_table.php

    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateExamsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('exams', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title');
                $table->integer('user_id')->unsigned();
                $table->foreign('user_id')->references('id')->on('users');
                $table->boolean('enable');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('exams');
        }
    }
    
  4. title:測驗的名稱
  5. user_id:建立測驗的使用者編號
  6. enable:是否啟用測驗, boolean() 在 MySQL 中其實是 tinyint(1) 類型,未來我們可能需要做一下型別轉換。
  7. 若是要建立 foreign key 必須在還沒有資料的時候就先建立,日後若已經有資料,要再建立 foreign key 就會比較麻煩。(因為必須資料能對應的起來才可以建立)

    $table->foreign('user_id')->references('id')->on('users');
  8. 建立各種欄位類型可參考:https://laravel-china.org/docs/laravel/5.6/migrations/1400#creating-columns

  9. 替欄位加入各種屬性請參考:https://laravel-china.org/docs/laravel/5.6/migrations/1400#column-modifiers

  10. 要修改欄位方法請參考:https://laravel-china.org/docs/laravel/5.6/migrations/1400#55682c

  11. 各種索引的建立請參考:https://laravel-china.org/docs/laravel/5.6/migrations/1400#b271e4

  12. 最後執行資料庫遷移即可建出新的資料表

    php artisan migrate
  13. 要看資料表是否順利建出可以連到http://localhost/phpmyadmin/db_structure.php?server=1&db=homestead
  14. 若想撤銷剛剛的動作,可執行:
    php artisan migrate:rollback
  15. 若想刪除全部資料表重來,可以執行

    php artisan migrate:reset

到GitHub觀看此單元程式異動


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbdsn%3D1157

計數器

今天: 2940294029402940
昨天: 3894389438943894
總計: 7449196744919674491967449196744919674491967449196