iT邦幫忙

第 11 屆 iThome 鐵人賽

1
Software Development

在後花園遇見LP,Laravel及PHP的甜蜜糾纏,火熱上映系列 第 44

✾後花園D44✾ Flower 留言版 CRUD Part 1( 會員留言板 model 及 migration )

本系列文的環境狀態,可點擊此連結後花園環境參考

如果這次做的留言版有想跟着一起做的看倌,因爲有用到之前的設定,建議回顧下列這篇連結的內容:
✾後花園D23✾-種花囉! Part 3( 會員系統 CRUD 之 Route 及 Middleware 設定 )

這次做的是跟 flower 有關聯的 Stone 留言版,會有 CRUD 的部份,就會像是個會員的留言版,只是我調換了一般常用的名稱,改用成 flower 跟 stone 取代,主要是爲減少名稱混肴的情形,看倌們就當作刻文在石碑上留言吧!

建立 Stone 的 model 及 migration

在 Terminal 輸入指令

$ php artisan make:model Stone -m

編輯 stones 的 migration 內容

路徑:database/migrations/{日期}_create_stones_table.php
填入程式碼

<?php

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

class CreateStonesTable extends Migration
{
    public function up()
    {
        Schema::create('stones', function (Blueprint $table) {
            $table->bigIncrements('id');
            // 建立 flower_id 的欄位
            $table->unsignedBigInteger('flower_id');
            // 建立標題與內文的欄位
            $table->string('title');
            $table->string('content');
            // $table -> 此 table 的 'flower_id' -> 參照指定的 table 欄位名 爲 'id' -> 指定的 table 爲 'flowers'
            $table->foreign('flower_id')->references('id')->on('flowers');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('stones');
    }
}

在 Terminal 輸入指令,執行 migrate

$ php artisan migrate

編輯 Stone 的 Model

路徑:app/Stone.php
填入程式碼

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;

class Stone extends Model
{
    use Notifiable;
    // 批量分配 ( mass assignment ) - 允許哪些欄位可直接存入資料庫 
    protected $fillable = ['flower_id', 'title', 'content'];

    public function flower()
    {
        // 建立跟 Flower 的關聯
        return $this->belongsTo('App\Flower');
    }
}

編輯 Flower 的 Model

路徑:app/Flower.php
填入程式碼

<?php
namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;


class Flower extends Authenticatable
{
    use Notifiable;
    protected $fillable = [
        'name', 'email', 'password', 'api_token'
    ];

    public function stone()
    {   
        // 建立跟 Stone 的關聯
        return $this->hasMany('App\Stone');
    }

    // 指定在模型做序列化 ( Serialization ) 給外界讀取時,需要隱藏的資料欄位
    protected $hidden = [
        'password',
    ];
}

今天就先建好 model 及 migration 部份,之後再一步一步來。

參考連結:

❁ Laravel 客製化使用者驗證功能-增加使用者資料欄位
❁ Ken 大 - ( Migration )
❁ Ken 大 - 貼文 ( Model ) [ 遇到一個坑 > < ]


上一篇
✾後花園D43✾-多元的 多 對 多 關係? Part 3( Many To Many Relationships 資料庫及 postman 運行 )
下一篇
✾後花園D45✾ Flower 留言版 CRUD Part 2( 會員留言板 新增文章 Controller )
系列文
在後花園遇見LP,Laravel及PHP的甜蜜糾纏,火熱上映49
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言