Defining enum columns in migrations for CodeIgniter 4

- Andrés Cruz

En español
Defining enum columns in migrations for CodeIgniter 4

We are going to know how we can use the enums to define our types in the database in CodeIgniter 4; which are a simple structure with some flexibility that we can use instead of foreign relationships that require a larger structure.

The enums are a very simple structure that allows us to define a set of fixed values for a column, we define it as if it were an array, therefore, the value of the record that we want to insert has to be included in that pool of data that we define. as an array.

Let's define a migration like the following:

class ProductsControl extends Migration
{
   public function up()
   {
       $this->forge->addField([
           'id' => [
               'type' => 'INT',
               'unsigned' => TRUE,
               'auto_increment' => TRUE
           ],
           'count'          => [
               'type'           => 'INT',
               'constraint'     => 5,
               'unsigned'       => TRUE
           ],
           'type'      => [
               'type'           => 'ENUM',
               'constraint'     => ['exit', 'entry'],
               'default'        => 'entry',
           ],
       ]);
       $this->forge->addKey('id', TRUE);
       $this->forge->createTable('products_control');
   }

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

Explanation of the previous code

It's a NORMAL migration in CodeIgniter 4, the important thing in this post, is the type call:

'type'      => [
               'type'           => 'ENUM',
               'constraint'     => ['exit', 'entry'],
               'default'        => 'entry',
           ],

In which we define the constraint, such as an array, in which we define the data pool, in this case, we are indicating that type can only contain one of the following values: 'exit', 'entry'; we define a default value, and little else.

As you can see, we have any structures or columns you want to define, and the enum, which is nothing more than a common C4 definition with an array defining values that you can use 'exit' and 'entry'

The rest of your columns can have the structure that you want, that your application needs, and for this example it is not important.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.