phpcakephpcakephp-4.x

Issue referencing a second database/datasource in my application


I'm having issues incorporating a second database into my application.

  1. I've created both connections in app.php and app_local.php
  2. The model (ie. BusinessRequests) referencing the second database implements defaultConnectionName()

Error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'app_a.business_requests' doesn't exist

Resulting SQL - note missing database/connection prefix when referencing BusinessRequests in the LEFT JOIN

SELECT
  Requests.id AS Requests__id,
  Requests.business_request_id AS Requests__business_request_id,
  Requests.notes AS Requests__notes,
  Requests.created AS Requests__created,
  Requests.modified AS Requests__modified,
  BusinessRequests.id AS BusinessRequests__id,
  BusinessRequests.title AS BusinessRequests__title,
  BusinessRequests.status AS BusinessRequests__status,
  BusinessRequests.created AS BusinessRequests__created,
  BusinessRequests.modified AS BusinessRequests__modified
FROM
  requests Requests
  LEFT JOIN business_requests BusinessRequests ON BusinessRequests.id = Requests.business_request_id
WHERE
  Requests.id = 1
LIMIT
  1

Database app_a (Note foreign key setup)

CREATE TABLE `requests` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `business_request_id` int(11) unsigned DEFAULT NULL,
  `notes` varchar(255) NOT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp(),
  `modified` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`),
  KEY `FK_requests_app_common.business_requests` (`business_request_id`),
  CONSTRAINT `FK_requests_app_common.business_requests` FOREIGN KEY (`business_request_id`) REFERENCES `app_common`.`business_requests` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci

Database app_common

CREATE TABLE `business_requests` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(255) NOT NULL,
  `status` varchar(255) NOT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp(),
  `modified` datetime NOT NULL DEFAULT current_timestamp(),
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=70270 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_520_ci

Content of app.php

  'Datasources' => [
    'default' => [
        'className' => Connection::class,
        'driver' => Mysql::class,
        'persistent' => false,
        'timezone' => 'UTC',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,
        'quoteIdentifiers' => false,
    ],

    'common' => [
        'className' => Connection::class,
        'driver' => Mysql::class,
        'persistent' => false,
        'timezone' => 'UTC',
        'flags' => [],
        'cacheMetadata' => true,
        'log' => false,
        'quoteIdentifiers' => false,
    ],
],

Content of app_local.php (mariadb is a Docker container)

'Datasources' => [
        'default' => [
            'host' => 'mariadb',
            'username' => 'root',
            'password' => 'root',
            'database' => 'app_a',
            'url' => env('DATABASE_URL', null),
        ],

        'common' => [
            'host' => 'mariadb',
            'username' => 'root',
            'password' => 'root',
            'database' => 'app_common',
            'url' => env('DATABASE_URL', null),
        ],
    ],

Content of BusinessRequestsTable.php

Here I specify the connection to use for the model.

public static function defaultConnectionName(): string
{
    return 'common';
}

Content of RequestsController.php

public function view($id = null)
{
    $request = $this->Requests->get($id, [
           'contain' => ['BusinessRequests'],
    ]);

    $this->set(compact('request'));
}

Solution

  • In this case, setting the prefix of the database (ie. app_common), when setting the table in the model, seemed to resolved the issue.

    public function initialize(array $config): void
    {
        parent::initialize($config);
    
        $this->setTable('app_common.business_requests');
        $this->setDisplayField('title');
        $this->setPrimaryKey('id');
    
        $this->addBehavior('Timestamp');
    }