Featured image of post Day 23. 實作 TODO 練習 上篇:前置作業

Day 23. 實作 TODO 練習 上篇:前置作業

資源

Laravel7 30天: 目錄
專案連結: github - laravel7 之 30 天分享

前言

專案連結: github - laravel7 之 30 天分享

上一篇: Day 22. CRUD 很簡單 Resource Controller

接下來準備實作 ToDo 的功能, 這是上篇主要建制一些前置作業

主要

todo 功能我會以 task(任務) 作為命名,
因為我感覺這樣比較直觀一點

資料庫設計

建立 Model + Migration

1
php artisan make:model Models/Task -m

編輯 Migration

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onUpdate('cascade')->onDelete('cascade');
            $table->string('title', 100)->comment('標題');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tasks');
    }
}

執行 Migration

1
php artisan migrate

調整 Model

  • 檔案 app/Models/Task.php

    1. 加入 fillable
    2. 關聯 user
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    
    class Task extends Model
    {
        protected $fillable = [
            'user_id', 'title'
        ];
    
        /**
        * 關聯會員
        * 
        * @return Illuminate\Database\Eloquent\Model User
        */
        public function user()
        {
            return $this->belongesTo(User::class);
        }
    }
    
  • 檔案 app/Models/User.php

    1. 關聯 Task (一對多)
     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    
    class User extends Authenticatable implements MustVerifyEmail
    {
    
        /**
        * 關聯 Task
        *
        * @return Illuminate\Database\Eloquent\Model Task
        */
        public function tasks()
        {
            return $this->hasMany(Task::class);
        }
    }
    

建立 Controller

1
php artisan make:controller TaskController -r

建立路由

1
Route::resource('tasks', 'TaskController');
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy