CakePHP 4 Custom Primary Key For Table Using Migration

Reading Time: 5 minutes
2,402 Views

Inside this article we will see CakePHP 4 custom primary key for table using migration. Article contains classified information about creating custom primary key for table schema using cakephp migration concept.

Migrations are those files which creates table schema for application. By default when we create migration and migrate, it creates “id” column as a default primary key.

Let’s assume we have a table schema for products. Product table contains columns and their attributes as –

  • product_id [INTEGER]
  • name [STRING]
  • cost [INTEGER]
  • product_image [STRING]
  • description [TEXT]
  • status [ENUM]
  • created_at [TIMESTAMP]

We want to create this products table with custom primary key as product_id.

CakePHP CLI gives a smart option to create migration files for schema. We will use bin/cake CLI to generate migration files.

Learn More –

Let’s get started.


CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.


Database Connection

Open app_local.php file from /config folder. Search for Datasources. Go to default array of it.

You can add your connection details here to connect with your database. It will be like this –

//...

'Datasources' => [
        'default' => [
            'host' => 'localhost',
            /*
             * CakePHP will use the default DB port based on the driver selected
             * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
             * the following line and set the port accordingly
             */
            //'port' => 'non_standard_port_number',

            'username' => 'root',
            'password' => 'sample@123',

            'database' => 'mydatabase',
            /*
             * If not using the default 'public' schema with the PostgreSQL driver
             * set it here.
             */
            //'schema' => 'myapp',

            /*
             * You can use a DSN string to set the entire configuration
             */
            'url' => env('DATABASE_URL', null),
        ],
  
     //...

//...

You can pass host, username, password and database.

Successfully, you are now connected with the database.


Create & Run Migration

Open project into terminal and run this command

$ bin/cake bake migration CreateProductsTable

This command will create a migration file inside /config/Migrations folder. File name will be prefixed with the timestamp value and look like 20220217030354_CreateProductsTable.php

Open migration file and write this code into it to create “products” table schema.

<?php

declare(strict_types=1);

use Migrations\AbstractMigration;

class CreateProductsTable extends AbstractMigration
{
    /**
     * Change Method.
     *
     * More information on this method is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     * @return void
     */
    public function change()
    {
        $table = $this->table('products', ['id' => false, 'primary_key' => ['product_id']]);

        $table->addColumn('product_id', 'integer', [
            'autoIncrement' => true,
            'limit' => 5
        ]);
        $table->addColumn('name', 'string', [
            'limit' => 120,
            'null' => false,
        ]);
        $table->addColumn('cost', 'integer', [
            'limit' => 5,
            'null' => false,
        ]);
        $table->addColumn('product_image', 'string', [
            'limit' => 220,
            'null' => true,
        ]);
        $table->addColumn('description', 'text', [
            'null' => true,
        ]);
        $table->addColumn('status', 'enum', [
            'values' => [1, 0],
            'default' => 1
        ]);
        $table->addColumn('created_at', 'timestamp', [
            'default' => 'CURRENT_TIMESTAMP',
            'null' => false,
        ]);

        //$table->addPrimaryKey("product_id");
        $table->create();
    }
}

By default when we create any migration, it takes id column as a primary key. We don’t need to define into code as well. Automatically it will create an “id” column into database table.

But in this case we want own primary key for table as product_id, then this way you can write your code for it.

First you need to disable auto creation of an “id” column to table, then give your column name.

$table = $this->table('products', ['id' => false, 'primary_key' => ['product_id']]);

OR

$table->addPrimaryKey("product_id");

Run Migrations

Back to terminal and run this command to migrate this migration. It will create table schema into database

$ bin/cake migrations migrate

When it executes we should see “products” table in database.

For more about datatypes and other information of migration you can click here for official document.

We hope this article helped you to learn about CakePHP 4 Custom Primary Key For Table Using Migration Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.