iT邦幫忙

2021 iThome 鐵人賽

DAY 24
0
自我挑戰組

後端新手PHP+Laravel筆記系列 第 24

[Day24]創建Table及撈取資料

創建migration遷移檔案

首先先使用artisan指令: make:migration
創建一個產品table的遷移檔案
php artisan make:migration create_products_table

更改遷移檔案加入欄位

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateProductTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->string('code'); // 生成varcher(255)
            $table->string('name'); 
            $table->integer('price'); // int(11)
            $table->integer('quantity'); 
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down() // 可以使用rollback回到上一部
    {
        Schema::dropIfExists('products');
    }
}

接著在cmd輸入:php migrate
會在MySQL生成以下Table
https://ithelp.ithome.com.tw/upload/images/20210922/20128999Z6TPaZkKJC.jpg

可以在資料庫新增幾筆資料
INSERT INTO test.products (code, name, price, quantity) VALUES ('2', 'computer', '1000', '10');

那要怎麼從Laravel搜尋資量表資料呢?
在cmd輸入: php artisan tinker
Tinker 可以允許您在命令行上與整個 Laravel 應用程序進行交互
接著在tinker中輸入 DB::select('select * from products');
https://ithelp.ithome.com.tw/upload/images/20210922/201289991PAp0hDQfB.jpg
成功撈取到資料庫資料囉


上一篇
[Day23]下載POSTMAN以及MYSQL
下一篇
[Day25] Query Builder查詢生產器
系列文
後端新手PHP+Laravel筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言