Laravel5.8で掲示板を作ってみる(3)

LaravelLaravel

概要

前回に引き続き、今回はDBを用意してテーブルを作成するところまで行います。
DBには簡単に使えるので、sqliteを使用します。

DBの設定

.env を書き換える

envのmysqlの箇所をsqliteに書き換えて、DB_HOSTから下をコメントアウトします。

DB_CONNECTION=sqlite
#DB_HOST=127.0.0.1
#DB_PORT=3306
#DB_DATABASE=homestead
#DB_USERNAME=homestead
#DB_PASSWORD=secret

database.sqliteファイルを作成する

下記のパスに中身は空のファイル(ファイル名:database.sqlite)を作成します。

codelike_bbs\database\database.sqlite

php artisan migrateを実行してみる

今回は使いませんが、下記のように初期から用意されているファイルを使ってテーブルが作成されます。

$codelike_bbs>php artisan migrate
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated:  2014_10_12_000000_create_users_table
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated:  2014_10_12_100000_create_password_resets_table

テーブルのコードは下記に用意されています。

codelike_bbsdatabasemigrations2014_10_12_000000_create_users_table.php

create_users_tableの中身

2つ最初から用意されていますが、ユーザーテーブルの中身を見てみると下記のようになっています。
upメソッドの中に定義を書いて、migrateを流すことでテーブルが作成されます。
こちらに使える型などが書いてあります。

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

エラーが発生した場合(IlluminateDatabaseQueryException : could not find driver (SQL: PRAGMA foreign_keys = ON;))

php.iniでpdo_sqliteがコメントアウトされていることがあるので外して試してみてください。

extension=pdo_sqlite

新しいテーブルを2つ作成する

掲示板用のテーブルを考える

上記までで、sqliteが動くことがわかったので、掲示板で使うテーブルのファイルを作成します。
boardテーブルが掲示板スレッドでmessageが返信用のテーブルです。

  • board テーブル
    ・id
    ・title:タイトル
    ・user_name:ユーザー名
    ・about_text:コメント
    ・password:パスワード
    ・created_at
    ・updated_at
    ・deleted_at

  • message テーブル
    ・id
    ・board_id:boardテーブルの主キー
    ・user_name:ユーザー名
    ・message:返信メッセージ
    ・created_at
    ・updated_at

モデルとDBファイルを作成する

DBにアクセスするためのモデルと、先ほどのDBマイグレーションファイルを一緒に作成します。

php artisan make:model [モデル名] -m

上記コマンドで作成します。 -mオプションはマイグレーションファイルを作成するという意味です。

$codelike_bbs>php artisan make:model Board -m
Model created successfully.
Created Migration: 2019_05_13_142849_create_boards_table
$codelike_bbs>php artisan make:model Message -m
Model created successfully.
Created Migration: 2019_05_13_143136_create_messages_table

コマンドを2つ打ってそれぞれファイルができると思います。

create_boards_table.php を編集する。

下記のようにします。

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateBoardsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('boards', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('title');
            $table->string('user_name');
            $table->string('about_text');
            $table->string('password');
            $table->timestamps();
            $table->softDeletes();
        });
    }

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

upメソッドにそれぞれのカラムを追加しました。
created_at / updated_at はtimestamps()で勝手に追加してくれます。
deleted_atはsoftDeletes()をかけば追加されます。

create_messages_table.php を編集する。

同様に下記のようにします。

<?php

use IlluminateSupportFacadesSchema;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class CreateMessagesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->bigInteger('board_id');
            $table->string('user_name');
            $table->string('message');
            $table->timestamps();
        });
    }

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

migrateを再実行

下記のようにマイグレーションが流れてテーブルができます。

$codelike_bbs>php artisan migrate
Migrating: 2019_05_13_142849_create_boards_table
Migrated:  2019_05_13_142849_create_boards_table
Migrating: 2019_05_13_143136_create_messages_table
Migrated:  2019_05_13_143136_create_messages_table

確認する

sqlite3をインストールしてsqliteコマンドを使えるようにしておけば作ったデータやテーブルを確認できます。
こちらでダウンロードできるので、適当なディレクトリに配置してパスを通しておきます。
linuxだとyumやapt-getで取ってこれると思います。

sqlite3 databasedatabase.sqlite

上記のようにsqlite3コマンドでファイルを引数に与えてあげると開きます

codelike_bbs>sqlite3 databasedatabase.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> .tables
boards           migrations       users
messages         password_resets
sqlite> .schema boards
CREATE TABLE IF NOT EXISTS "boards" ("id" integer not null primary key autoincrement, "title" varchar not null, "user_name" varchar not null, "about_text" varchar not null, "password" varchar not null, "created_at" datetime null, "updated_at" datetime
null, "deleted_at" datetime null);
sqlite> .schema messages
CREATE TABLE IF NOT EXISTS "messages" ("id" integer not null primary key autoincrement, "board_id" integer not null, "user_name" varchar not null, "message" varchar not null, "created_at" datetime null, "updated_at" datetime null);

.tablesコマンドで作られているテーブル、.schemaコマンドでテーブルのcreate文が確認できます。
boardsとmessagesができていればOKです。

githubのbranch example3に今回のコードを置いてます。

コメント

  1. […] Laravel5.8で掲示板を作ってみる(3) […]

タイトルとURLをコピーしました