Laravel - データベース - テーブル作成


クラウディア 


1. 概要
2. テーブル作成
3. クラス作成
4. insert
5. 参考サイト

1. 概要

 「Laravel」では、「migration」という仕組みを利用して、データベースのテーブルを作成することができます。  (「migration」という仕組みは、この手のフレームワークには付き物のようです)

2. 作成

 データベース自体は作成済で、接続設定も。

.env
 には、定義済であるとして。  データベースサーバは、「PostgreSQL」で、下記のテーブル(「Laravel」としてはいささか変則)

create table lograw
(
    address inet not null
  , agent text
  , referer text
  , created_at timestamp not NULL
  , primary key (addres, created_at)
);
comment on table lograw is '生ログ';
comment on column lograw.address is 'アドレス';
comment on column lograw.agent is 'ブラウザ';
comment on column lograw.referer is 'リンク元';
comment on column lograw.created_at is 'アクセス';
 下記のファイルを作成して。  (「YYYY_MM_DD_HHMMSS」は数字で日時を記述)

database/migrations/YYYY_MM_DD_HHMMSS_create_lograw_table.php
 下記の内容を記述します。

<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('lograw', function (Blueprint $table)
		{
            $table->string('address')->comment('アドレス');
            $table->text('agent')->nullable()->comment('ブラウザ');
            $table->text('referer')->nullable()->comment('リンク元');
            $table->timestamp('created_at', 6)->comment('アクセス');

            $table->primary(['address', 'created_at']);
        });

        DB::statement("COMMENT ON TABLE lograw IS '生ログ'");
    }

    public function down(): void
    {
        Schema::dropIfExists('lograw');
    }
};
 「address」カラムを「string」で定義しますが、「Laravel」に、「inet」がないためで、後で変更します。  テーブルを作成します。  パーミッションの問題があるので、ここは、「root」ユーザ権限で。

php artisan migrate

   INFO  Running migrations.

  YYYY_MM_DD_HHMMSS_create_lograw_table ....
 これで、テーブルが作成されます。  作成後に、「psql」か何かで、「address」カラムの型を変更します。

alter table lograw alter column address type inet using address::inet;

3. クラス作成

 ここ、話が前後しちゃいますが。  前項で作成したテーブルのモデルクラスを作成します。  パーミッションの問題があるので、ここは、「root」ユーザ権限で作成しておいて、必要であれば後でパーミッションを変更します。

php artisan make:model Lograw
 下記のファイルが、作成され。

app/Models/Lograw.php
 中身がこんななっています。

<?php

namespace App\Models;

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

class Lograw extends Model
{
    use HasFactory;
}
 使えるようにするために、クラス内に下記を記述します。

class Lograw extends Model
{
    use HasFactory;

    protected $table = 'lograw';

    public $incrementing = false;
    protected $primaryKey = null;
    public $timestamps = false;
	protected $fillable = [ 'address', 'agent', 'referer', 'created_at' ];
}

4. insert

 前項のクラスに「insert」メソッドを追加します。

    public static function insertNow(string $address, ? string $agent = null, ? string $referer = null): void
	{
    	static::query()->insert([
			'address'    => $address,
			'agent'      => $agent,
			'referer'    => $referer,
			'created_at' => DB::raw('now()'),
    	]);
	}
 では、キー重複エラーが怖いので、万一を考えて。

    public static function insertNow(string $address, ? string $agent = null, ? string $referer = null): void
	{
		DB::statement(
			'insert into ' . (new static)->getTable() .' '
			.'(address, agent, referer, created_at) '
			.'values (?, ?, ?, now()) '
			.'on conflict do nothing ',
			[$address, $agent, $referer]
		);
	}
 「on conflict do nothing」は、「Laravel」には用意されていないらしいので、べたな「SQL」を使うしかないようです。

5. 参考サイト

 本ページは、「ChatGPT」くんを参考にさせていただきました。

EaseUS
AbemaTV 無料体験
5G CONNECT
アフィリエイトのアクセストレード