フルスタックかつ軽量!CodeIgniterを試す-DB編

こんにちは、コバヤシです。 前回に引き続きCodeIgniterをさわっていきます。
今回はDBまわりについて書いていきたいと思います。

tech.arms-soft.co.jp

マイグレーションを行う

まずはマイグレーションから行っていきます。

sparkコマンドでマイグレーションファイルを作成します。

php spark make:migration CreateUser --suffix

app/Database/Migrations/ディレクトリ以下にマイグレーションファイルが作成されるので、これを修正します。

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateUserMigration extends Migration
{
    public function up()
    {
        $this->forge->addField([
                   'id' => [
                       'type'           => 'BIGINT',
                       'constraint'     => 5,
                       'unsigned'       => true,
                       'auto_increment' => true,
                   ],
                   'name' => [
                       'type'       => 'VARCHAR',
                       'constraint' => '100',
                   ],
                   'email' => [
                       'type'       => 'VARCHAR',
                       'constraint' => '100',
                       'null' => true,
                   ],
                   'created_at' => [
                       'type' => 'DATETIME',
                       'null' => true,
                   ],
                   'updated_at' => [
                       'type' => 'DATETIME',
                       'null' => true,
                   ],
                   'deleted_at' => [
                       'type' => 'DATETIME',
                       'null' => true,
                   ],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

    public function down()
    {
        $this->forge->dropTable('users');
    }
}

laravelのように、created_at、updated_at、deleted_atを作成するコマンドが無かったので直接作成をしています。

マイグレーションは以下のコマンドで実行します。

php spark migrate

ロールバックは以下のコマンドです。

php spark migrate:rollback

モデルを作成する

次にモデルの作成を行います。
モデルの作成もコマンドから行います。

php spark make:model User --suffix

app/Models/ディレクトリ以下にモデルファイルが作成されます。

<?php

namespace App\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [];

    // Dates
    protected $useTimestamps = false;
    protected $dateFormat    = 'datetime';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_at';
    protected $deletedField  = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks = true;
    protected $beforeInsert   = [];
    protected $afterInsert    = [];
    protected $beforeUpdate   = [];
    protected $afterUpdate    = [];
    protected $beforeFind     = [];
    protected $afterFind      = [];
    protected $beforeDelete   = [];
    protected $afterDelete    = [];
}

作成されたモデルファイルを少し修正します。

<?php
    protected $allowedFields    = [
        'name',
        'email'
    ];

$allowedFieldsは変更可能なフィールドを指定します。Laravelでいうところの$fillableと同じですね。

<?php
    protected $useTimestamps = true;

trueにすると作成時、更新時にcreated_at、updated_atに日時が入るようになります。

<?php
    protected $useSoftDeletes   = true;

trueにすると論理削除が有効になります。

データを作成する

<?php

namespace App\Controllers;

use App\Models\UserModel;

class Test extends BaseController
{
    public function index()
    {
        $model = new UserModel();
        
        $model->insert([
            'name' => 'コバヤシ',
            'email' => 'xxxx@arms-soft.co.jp'
                       ]);
        
        return bladeView('test');
    }
}

モデルのinsertメソッドを使用してデータの作成を行います。引数としてフィールド名をキーとして値を渡せばOKです。
有効なキーはモデルの$allowedFieldsで指定したフィールド名のみとなります。

データを抽出する

<?php

namespace App\Controllers;

use App\Models\UserModel;

class Home extends BaseController
{
    public function index()
    {
        $model = new UserModel();
        
        $result = $model
            ->where('name', 'コバヤシ')
            ->first();
        
        var_dump($result);
    }
}

モデルのwhereメソッドで条件を指定して、firstで1件データを取得しています。このあたりはlaravelのORMと同じですね。プライマリーキーでの検索であればfindを使用しましょう。

ソートを指定する場合はorderByメソッドを使用します。

<?php
        $result = $model->orderBy('id', 'desc')->findAll();

複数行のデータ取得はfindAllメソッドになります。

次にorとandが混ざった抽出です.。

<?php
        $result = $model->groupStart()
            ->where('id', 1)
            ->orWhere('id', 3)
            ->groupEnd()
            ->like('email', 'arms-soft.co.jp')
            ->findAll();

条件を括弧で括るには、groupStartメソッドとgroupEndメソッドを使用します。
上記の例では、以下のようなSQL文が発行されます。

SELECT * FROM `users` WHERE ( `id` = 1 OR `id` = 3 ) AND `email` LIKE '%arms-soft.co.jp%' ESCAPE '!' AND `users`.`deleted_at` IS NULL

FuelPHPのORMに近い形ですね。

データの削除

<?php

        $result = $model->where('id', 1)->delete();

削除にはモデルのdeleteメソッドを使用します。モデルで$useSoftDeletesをtrueにしている為、実行するとdeleted_atのカラムに実行した日時が入りました。

ちなみに、論理削除されたデータを含めて抽出する場合は、withDeletedメソッドを使用します。

<?php

        $result = $model->withDeleted()->findAll();

削除されたデータのみ抽出する場合は、onlyDeletedメソッドです。

<?php

        $result = $model->onlyDeleted()->findAll();

まとめ

ざっくりとCodeIgniterのDBまわりをさわってみました。今まで使用してきたフレームワークとさほど変わらない感じなので違和感なく使用することが出来ました。今後も実際の案件で使用できるよう調査を進めて行きたいと思います。