:::

9-1 編輯並執行商品(Product)的 migrate 檔案

一、編輯商品 migrate 檔案

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

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

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

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

    php artisan make:migration create_products_table --create=products
  3. 編輯 \專案\database\migrations\日期_create_products_table.php

    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    class CreateProductsTable extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('products', function (Blueprint $table) {
                $table->increments('id');
                $table->string('title');
                $table->text('description');
                $table->string('image');
                $table->boolean('on_sale')->default(true);
                $table->unsignedInteger('price');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::dropIfExists('products');
        }
    }
    
    • id :自動編號,其用increments()即可,原本的bigincrements()有點太大了。
    • title:商品的名稱,用string()來建立字串欄位
    • description:商品的說明,用text()來建立大量文字欄位
    • image:商品的圖片路徑,用string()來建立字串欄位
    • on_sale:是否啟用商品, boolean() 在 MySQL 中其實是 tinyint(1) 類型,未來我們可能需要做一下型別轉換。另外,我們用default(true)來設定欄位預設值為true
    • price:商品的價格,用unsignedInteger()來產生正整數數字欄位
  4. 建立各種欄位類型可參考:https://learnku.com/docs/laravel/5.8/migrations/3928#creating-columns

  5. 替欄位加入各種屬性請參考:https://learnku.com/docs/laravel/5.8/migrations/3928#column-modifiers

  6. 要修改欄位方法請參考:https://learnku.com/docs/laravel/5.8/migrations/3928#modifying-columns

  7. 各種索引的建立請參考:https://learnku.com/docs/laravel/5.8/migrations/3928#creating-indexes

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

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

    php artisan migrate:reset

到GitHub觀看此單元程式異動


:::

書籍目錄

展開 | 闔起

http%3A%2F%2Fcampus-xoops.tn.edu.tw%2Fmodules%2Ftad_book3%2Fpage.php%3Ftbsn%3D43%26tbdsn%3D1409

計數器

今天: 1930193019301930
昨天: 1988198819881988
總計: 7388821738882173888217388821738882173888217388821