Home > Mobile >  codeigniter 4 migration file not creating table
codeigniter 4 migration file not creating table

Time:03-28

when I first made a migration file for table users, the public function down() in the migration file was empty. when I run php spark migrate the table users was created.

then I generated another migration file with php spark make:migration users, made a few adjustments according to the new table structure and put $this->forge->dropTable('users'); in the public function down(). but when I run php spark migrate again, the users table doesn't have the new field..

I'm using codeigniter 4 and mysql. here's my code

UserModelphp

<?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;
    // added created_at and updated_at
    protected $allowedFields = ['username', 'password', 'foto', 'nama', 'email', 'telepon', 'created_at', 'updated_at'];

    // 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    = [];
}

first migration file

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
    public function up()
    {
        // tabel users
        $this->forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 7,
                'auto_increment' => true,
            ],
            'username' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
                'null' => false,
            ],
            'password' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => false,
            ],
            'profile_pic' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
            ],
            'nama' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
            ],
            'email' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
            ],
            'telepon' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
            ],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

    public function down()
    {
        // hapus tabel users
    }
}

new migration file

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class Users extends Migration
{
    public function up()
    {
        // tabel users
        $this->forge->addField([
            'id'       => [
                'type'           => 'INT',
                'constraint'     => 7,
                'auto_increment' => true,
            ],
            'username' => [
                'type'       => 'VARCHAR',
                'constraint' => 50,
                'null'       => false,
            ],
            'password' => [
                'type'       => 'VARCHAR',
                'constraint' => 255,
                'null'       => false,
            ],
            'foto'     => [
                'type'       => 'VARCHAR',
                'constraint' => 50,
            ],
            'nama'     => [
                'type'       => 'VARCHAR',
                'constraint' => 50,
            ],
            'email'    => [
                'type'       => 'VARCHAR',
                'constraint' => 100,
            ],
            'telepon'  => [
                'type'       => 'VARCHAR',
                'constraint' => 10,
            ],
            'created_at DATETIME DEFAULT CURRENT_TIMESTAMP',
            'updated_at DATETIME DEFAULT CURRENT_TIMESTAMP',
        ]);
        $this->forge->addKey('id', true);
        $this->forge->createTable('users');
    }

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

can someone tell me what I'm doing wrong? any help is appreciated

CodePudding user response:

Explanation:

The down() method isn't called when you execute php spark migrate.

The down() method is run when you perform a migration rollback process using php spark migrate:rollback.

Solution:

Add the $this->forge->dropTable('users'); line of code at the beginning of the up() method of the "new migration file".

new migration file

// ...
class Users extends Migration
{
    public function up()
    {
        $this->forge->dropTable('users');

         // ...
    }
    // ....
}

The purpose of the down() method is to "reverse" everything performed in the up() method.


Extra Notes:

Considering that in your new migration, you're only renaming an existing table column (profile_pic -> foto) and adding timestamp columns, it would make more sense if you specified a more meaningful "migration name".

In addition, instead of dropping & recreating the existing table, modify the table instead. I.e:

new migration file

A. Command (Create the new migration):

php spark make:migration alter_users_rename_profile_pic_add_timestamps

B. Generated migration.

<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AlterUsersRenameProfilePicAddTimestamps extends Migration
{
    private $tableName = "users";

    public function up()
    {
        $this->forge->modifyColumn($this->tableName, [

            "profile_pic" => [
                'name' => 'foto',
                'type' => 'VARCHAR',
                'constraint' => 50,
            ]
        ]);

        $this->forge->addColumn($this->tableName, [
            'created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP',
            'updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP',
        ]);

    }

    public function down()
    {
        $this->forge->modifyColumn($this->tableName, [

            "foto" => [
                'name' => 'profile_pic',
                'type' => 'VARCHAR',
                'constraint' => 50,
            ]
        ]);

        $this->forge->dropColumn($this->tableName, ["created_at", "updated_at"]);

    }
}

  • Related