iT邦幫忙

0

[Day 45] 留言板後台及前台(一) - 新增資料庫欄位

  • 分享至 

  • xImage
  •  

留言板後台及前台

新增資料庫欄位

接下來終於進入到留言板的部分,
之前的心情隨筆是記錄自己的情況,
後面留言板則是每個人都可以來給使用者留言,
留言板目前的欄位如下
https://ithelp.ithome.com.tw/upload/images/20210425/20105694KfPEIhexNP.png
這裡的user_id是指留言的使用者的id,
但是忽然發現少記錄了這是屬於誰的留言板,
所以我們要新增一個board_id欄位,
正好可以順便說一下怎麼新增欄位,
忘記之前migration的可以參考第10篇跟第11篇,
首先我們要新增一個migration檔案,
可以在Cmder輸入以下內容:
php artisan make:migration add_board_id_to_board_table
https://ithelp.ithome.com.tw/upload/images/20210425/201056949SB1YoZdVd.png

這樣子就會新增一個migration檔案
https://ithelp.ithome.com.tw/upload/images/20210425/20105694qWFtvbWsjX.png

然後進去編輯檔案如下

<?php

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

class AddBoradIdToBoardTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('board', function (Blueprint $table) {
            //加入board_id欄位到user_id欄位後方
            $table->integer('board_id')
                ->after('user_id');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('board', function (Blueprint $table) {
            //移除欄位
            $table->dropColumn('board_id');
        });
    }
}

up那邊表示我們要在board這個資料表,
user_id欄位之後新增一個board_id欄位,
down那邊表示要移除欄位,
這些都是給migration執行指令的時候看的.

之後執行migration指令
php artisan migrate
https://ithelp.ithome.com.tw/upload/images/20210425/20105694y6FYYPF5kX.png

我們再去資料庫看就發現新增了一個欄位
(目前沒有資料, 如果是有了資料要新增, 會需要給一個預設值)
https://ithelp.ithome.com.tw/upload/images/20210425/20105694ixlbQk8OEZ.png

並且修改 app/Entity/Board.php如下

<?PHP
namespace App\Entity;

use Illuminate\Database\Eloquent\Model;

class Board extends Model {
    //資料表名稱
    protected $table = 'board';

    //主鍵名稱
    protected $promaryKey = 'id';

    //可以大量指定異動的欄位(Mass Assignment)
    protected $fillable = [
        'user_id',
        'board_id',
        'email',
        'picture',
        'content',
        'enabled',
    ];
}
?>

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言