0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Laravel データ作成 テーブル作成編

Last updated at Posted at 2023-08-13

はじめに

今回は前準備としてテーブル作成から始める。
Laravelのマイグレーションでテーブルを作成する。

作成するテーブル

以下の3つのテーブルを作成する。
具体的には、「users」テーブル、「projects」テーブル、「tasks」テーブルをまず作成する。

Usersテーブル: 各ユーザの情報を記録する。
Projectsテーブル: 各プロジェクトの情報を記録する。ユーザとプロジェクトは多対多の関係になる可能性があり、中間テーブルを用意する。
Tasksテーブル: 各タスクの情報を記録する。このテーブルにはプロジェクトとのリレーションを設定する。

マイグレーション

マイグレーションでテーブル作成する
以下コマンドでマイグレーションファイルを作る
php artisan make:migration create_projects_table
php artisan make:migration create_project_user_table
php artisan make:migration create_tasks_table

postsテーブル

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

class CreateProjectsTable extends Migration
{
    public function up()
    {
        Schema::create('projects', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id')->after('id');
            $table->string('title');
            $table->text('description')->nullable();
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

        });
    }

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

ーーー

project_user(中間テーブル)

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('project_user', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('project_id');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
        });
    }

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

ーーー

tasksテーブル

<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('project_id');
            $table->string('title');
            $table->boolean('completed')->default(false);
            $table->text('description')->nullable();
            $table->dateTime('due_date')->nullable();
            $table->dateTime('completed_at')->nullable();
            $table->string('status')->default('pending');
            $table->timestamps();

            $table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
        });
    }

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

なお、usersテーブルに関しては、通常、Laravelの新しいプロジェクトを作成する際に、デフォルトでusersテーブルのマイグレーションファイルが含まれている。今回はそのusersのマイグレーションを使用しusersのテーブルを作成する。

php artisan migrateでテーブルが作成される。

Model対応

データ表示の時、コントローラでUser::with('projects.tasks')->find($id);を使用する予定である。そのためにはEloquentの活用を行うことになる。
Userモデルと Project モデル、Task モデルの間にリレーションシップを定義する必要がある。
それによりUserモデルからprojects.tasks のようにネストされたリレーションをロードすることが可能になる。

Projectモデル

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'description'];

       //以下追加
    public function tasks()
    {
        return $this->hasMany(Task::class);
    }
}

ここでは$fillableプロパティを使用して、titleとdescriptionフィールドが一括代入可能であることを示している。これにより、Seederなどからデータを挿入する際に、これらのフィールドへの代入が可能になる。
他テーブルも同様。

Userモデル

User.php
<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class User extends Authenticatable
{
    ...
    //以下追加
    public function projects()
    {
        return $this->hasMany(Project::class);
    }
    ...
}

Taskモデル

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'description',
        'due_date',
        'completed',
        'project_id',
    ];

    /**
     * Get the project that owns the task.
     */
       //以下追加
    public function project()
    {
        return $this->belongsTo(Project::class);
    }
}

今回において

今回はデータ作成の準備である。
そのためのテーブル作成、Eloquentの対応を行なった。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?