:::
9-1 編輯並執行商品(Product)的 migrate 檔案
一、編輯商品 migrate 檔案
-
migrate 檔案就是用來定義資料表欄位的檔案,屆時可用指令自動建立(或增減)資料表欄位
-
先確定
\專案\.env中的資料庫設定有設定正確 -
確定有啟動MySQL資料庫,並確定已經建立 DB_DATABASE 定義的資料庫
-
-
確認有無
\專案\database\migrations\日期_create_products_table.php(上一節有做了),若是還沒有上述檔案(或者是只要建立資料表,但不需要建立Model的時候),執行以下語法會自動生出 migrate 檔案(其中,是create_products_table檔案名稱,--create=products則是資料表名稱,慣例為複數):php artisan make:migration create_products_table --create=products -
編輯
\專案\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)來設定欄位預設值為trueprice:商品的價格,用unsignedInteger()來產生正整數數字欄位
-
建立各種欄位類型可參考:https://learnku.com/docs/laravel/5.8/migrations/3928#creating-columns
-
替欄位加入各種屬性請參考:https://learnku.com/docs/laravel/5.8/migrations/3928#column-modifiers
-
要修改欄位方法請參考:https://learnku.com/docs/laravel/5.8/migrations/3928#modifying-columns
-
各種索引的建立請參考:https://learnku.com/docs/laravel/5.8/migrations/3928#creating-indexes
-
最後執行資料庫遷移即可建出新的資料表
php artisan migrate - 要看資料表是否順利建出可以連到http://localhost/phpmyadmin/db_structure.php?server=1&db=homestead

- 若想撤銷剛剛的動作,可執行:
php artisan migrate:rollback -
若想刪除全部資料表重來,可以執行
php artisan migrate:reset
9. 建立商品模型
