2020年4月13日

Laravel Mirgrate 建立資料庫 (Mac)

以前建立資料庫,很直覺的就是開啟phpMyAdmin,然後資料庫表格設定一下就好了。
沒想到這個年代(好啦,我很老了),都用終端機指令建資料庫。
話不多說了,來指令建立吧。

誒~還是要開phpMyAdmin建立一個資料庫

















第二步,建立資料表,在終端機使用指令
php artisan make:migration create_links_table --create=links

這個指令會在database/migrations/ 新增一個{{datetime}}_create_links_table.php檔案
打開這個檔案,新增幾個欄位




















第三步,終端機上Mirgrate 資料庫
php artisan migrate






這時候,你就可以看到php檔案中的欄位已經幫你在資料庫中建立好了


另外,因為資料庫是新建的,沒有資料在裡面,通常為了測試,都需要自己建立很多資料,這時,migration也幫你做好這一塊了,只要做以下幾個步驟 ,測試資料也會自動幫你新增到資料庫喔。

第一步,終端機指令建立factory file
php artisan make:model --factory Link

然後打開database/factories/LinkFactory.php
加入以下程式碼

$factory->define(App\Link::class, function (Faker $faker) { return [ 'title' => substr($faker->sentence(2), 0, -1), 'url' => $faker->url, 'description' => $faker->paragraph, ]; });

第二步,終端機指令建立seeder
php artisan make:seeder LinksTableSeeder

然後打開database/seeds/LinksTableSeeder.php
加入以下程式碼

public function run() { factory(App\Link::class, 5)->create(); }

第三步,啟動LinkTableSeeder
打開database/seeds/DatabaseSeeder.php
加入以下程式碼

public function run() { $this->call(LinksTableSeeder::class); }

第四步,終端機指令新增測試資料到資料庫中
(注意,資料庫中最好不要有真實資料存在,不然會被清光光
php artisan migrate:fresh --seed

完成!

參考資料:https://laravel-news.com/your-first-laravel-application

沒有留言: