CakePHP 4 How To Work With One To One Relationship

Reading Time: 8 minutes
2,307 Views

Inside this article we will see CakePHP 4 How to work with one to one relationship. Article contains classified information about relationship in cakephp. We will see an example of using one to one relation which makes you understand of cakephp association.

A one-to-one relationship is a type of cardinality that refers to the relationship between two entities A and B in which one element of A may only be linked to one element of B, and vice versa.

For example, we have two tables like employees and addresses. Single employee has a single address into addresses table which will be one to one relationship.

Learn More –

Let’s get started.

What is one-to-one relationship?

A one-to-one relationship is a type of cardinality that refers to the relationship between two entities A and B in which one element of A may only be linked to one element of B, and vice versa.

Here,

You can see we have two tables Table1 and Table2. A single row of Table1 has a single associated data in Table2. This is kind of one to one row between tables.

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.

Create Database

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE mydatabase;

Successfully, we have created a database.

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 Migrations

Open project into terminal and run bake console commands to create migrations for application.

$ bin/cake bake migration CreateEmployees

$ bin/cake bake migration CreateAddresses

Above commands will create two migration files – 20220326133952_CreateEmployees.php and 20220326134000_CreateAddresses.php.

Open 20220326133952_CreateEmployees.php and write this following code into it.

<?php

declare(strict_types=1);

use Migrations\AbstractMigration;

class CreateEmployees extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('employees');
        $table->addColumn("name", "string", [
            "limit" => 50,
            "null" => false
        ]);
        $table->addColumn("email", "string", [
            "limit" => 50,
            "null" => false
        ]);
        $table->addColumn("mobile", "string", [
            "limit" => 20,
            "null" => false
        ]);
        $table->create();
    }
}

It will create employees table in database.

Open 20220326134000_CreateAddresses.php and write this following code into it.

<?php

declare(strict_types=1);

use Migrations\AbstractMigration;

class CreateAddresses extends AbstractMigration
{
    public function change()
    {
        $table = $this->table('addresses');
        $table->addColumn("employee_id", "integer", [
            "limit" => 5,
            "null" => false
        ]);
        $table->addColumn("details", "string", [
            "limit" => 150
        ]);
        $table->create();
    }
}

It will create addresses table into database.

Run Migration

Back to terminal and run this command to create tables.

$ bin/cake migrations migrate

Table: employees

Table: addresses

Sample Data For Tables

We will insert some fake data to test our application. Here, we have some mysql queries, you can copy and run for fake data.

Fake data for employees table.

--
-- Dumping data for table `employees`
--

INSERT INTO `employees` (`id`, `name`, `email`, `mobile`) VALUES
(1, 'Sanjay Kumar', 'sanjay@gmail.com', '1234567895'),
(2, 'Ashish Kumar', 'ashish@gmail.com', '7412589635'),
(3, 'Vijay Kumar', 'vijay@gmail.com', '9632587410');

Fake data for addresses table.

--
-- Dumping data for table `addresses`
--

INSERT INTO `addresses` (`id`, `employee_id`, `details`) VALUES
(1, 2, 'Sample Address 2, Colony 2, State 2, 11000'),
(2, 1, 'Sample Address 2, Colony 2, State 2, 22000'),
(3, 3, 'Sample Address 3, Colony 3, State 3, 33000');

Create Model & Entity

Now, we need to models and entities for application. Back to terminal and run these commands.

$ bin/cake bake model Employees --no-rules --no-validation

$ bin/cake bake model Addresses --no-rules --no-validation

It will create EmployeesTable.php and Employee.php for Employees. Also AddressesTable.php and Address.php in folders of /src/Model/Table and /src/Model/Entity.

Open EmployeesTable.php and write this following code into it.

<?php
declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class EmployeesTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('employees');
        $this->setPrimaryKey('id');

        $this->hasOne('emp_address', [
            'className' => 'Addresses',
        ]);
    }
}

Concept

$this->hasOne('emp_address', [
    'className' => 'Addresses',
]);

emp_address is the association name between employees and addresses tables. We will use this key to get data relational data between employees and addresses table. Here, a single employee has a single address.

Open AddressesTable.php and write this following code into it.

<?php

declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Table;

class AddressesTable extends Table
{
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('addresses');
        $this->setPrimaryKey('id');
    }
}

Create Controller & Run Application

Back to terminal and run this bake console command to create controller.

$ bin/cake bake controller Site --no-actions

It will create SiteController.php into /src/Controller folder. Open this file and write this code into it.

<?php

declare(strict_types=1);

namespace App\Controller;

class SiteController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();

        $this->loadModel("Employees");
        $this->autoRender = false;
    }

    public function getDetails()
    {
        $employees = $this->Employees->find("all")->contain([
            "emp_address"
        ])->toList();

        echo "<pre>";
        print_r($employees);
    }
}

Concept

Single employee is connected with single address details of Addresses table.

$employees = $this->Employees->find("all")->contain([
    "emp_address"
])->toList();

Once we execute this code then we will get output like this. It will dump data into output screen.

Let’s iterate over arrays, and read row by row data from it.

//...

if (count($employees) > 0) {
    foreach ($employees as $emp) {
        echo "Name: " . $emp->name . ", Address: " . $emp->emp_addres->details . "<br/>";
    }
}

We hope this article helped you to learn CakePHP 4 How To Work With One To One Relationship 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.