iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 27
1
Software Development

從零開始的Laravel RESTful api系列 第 27

Day 27 : category ( migration & Model )

接下來終於進入最後的 category 部份啦,為了省略多餘步驟,migration 和 Model 會一起建立。

$ php artisan make:model Category -m

Migration

此處的 category 只需要一個 name 欄位就行

*YYYY_MM_DD_XXXXXX_create_categories_table.php

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

除此之外,由於 category 和 post 之間是屬於多對多的關係,因此我們還需要一個 pivot table,這個 pivot table 就不需要建立與其相關的 Model

$ php artisan make:migration create_category_post_table

此 pivot table 可以彙整多對多關聯的資料,欄位內填入 category 和 post 的 id,以及將其設為 foreign key。

    public function up()
    {
        Schema::create('category_post', function (Blueprint $table) {
            // $table->bigIncrements('id');
            $table->unsignedBigInteger('category_id');
            $table->unsignedBigInteger('post_id');
            // $table->timestamps();
            
            $table->foreign('category_id')->references('id')->on('categories');
            $table->foreign('post_id')->references('id')->on('posts');
        });
    }

接下來就把這兩個 migration 進行 migrate

$ php artisan migrate

Model

首先先來定義 Category 的 model:

  • mass assignment
    在 Category 也只有 name 這個欄位可以填

    *Category.php

    protected $fillable = ['name'];
    
  • 關聯性

    Category 和 Post 之間為多對多的關係

    *Category.php

    public function posts(){
        return $this->belongsToMany(Post::class);
    }
    

    *Post.php

    public function categories(){
        return $this->belongsToMany(Category::class)
    }
    

    <補充> hasMany() 用於一對多的關係,不應該用於多對多的情況

下一篇來介紹比較不一樣的主題。

參考資料:

  1. Many to many relationship : https://laravel.com/docs/6.x/eloquent-relationships#many-to-many
  2. hasMany vs belongsToMany in laravel 5.x : https://stackoverflow.com/questions/36208460/hasmany-vs-belongstomany-in-laravel-5-x

上一篇
Day 26 : Policy authorization
下一篇
Day 28 : database seeding
系列文
從零開始的Laravel RESTful api30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言