Im a beginner of CakePHP and I have run into a problem.
I have two tables that resides in different databases on the same SQL Server. I can load data from them respetively but not via associations.
Basically I have a Locations table and a Customers table. The Locations belongsTo Customers and Customers hasMany Locations.
When I have a list of all Locations I load the customer_id, address, zip_code, city and country_code, But instead of getting the customer_id from the Locations table I would like to get the name and nr (name of the customer code/number in the Customer table). Another thing to mention is that the table name for the customers table is not following naming conventions (is called tblCustomer).
Im using Jerremy Harris LazyLoad plugin but getting an error:
SQLSTATE[42S02]: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name ‘tblCustomer’.
My code:
src\Model\Table\LocationsTable.php:
<?php // src/Model/Table/LocationsTable.php namespace App\Model\Table; use Cake\ORM\Table; class LocationsTable extends Table { public function initialize(array $config): void { $this->belongsTo('Customers', [ foreignKey' => 'customer_id' ]); $this->addBehavior('Timestamp'); } }
src\Model\Table\CustomersTable.php:
<?php // src/Model/Table/CustomersTable.php namespace App\Model\Table; use Cake\ORM\Table; class CustomersTable extends Table { public static function defaultConnectionName(): string { return 'db2'; } public function initialize(array $config): void { $this->setTable('tblCustomer'); $this->hasMany('Locations'); $this->addBehavior('Timestamp'); } }
src\Model\Entity\Location.php:
<?php // src/Model/Entity/Location.php namespace App\Model\Entity; use Cake\ORM\Entity; use JeremyHarris\LazyLoad\ORM\LazyLoadEntityTrait; class Location extends Entity { use LazyLoadEntityTrait; protected $_accessible = [ '*' => true, 'id' => false, ]; }
src\Controller\LocationsController.php:
<?php // src/Controller/LocationsController.php namespace App\Controller; class LocationsController extends AppController { public function index() { $locations = $this->Locations->find('all'); $this->set(compact('locations')); } }
templates\Locations\index.php:
<!-- File: templates/Locations/index.php --> <h1>Locations</h1> <table> <tr> <th>Id</th> <th>Customer</th> <th>Address</th> <th>City</th> <th>Created</th> </tr> <?php foreach ($locations as $location): ?> <tr> <td> <?= $this->Html->link($location->id, ['action' => 'view', $location->id]) ?> </td> <td> <?= $location->customer->nr ?> - <?= $location->customer->name ?> </td> <td> <?= $location->address_1 ?> </td> <td> <?= $location->city ?> </td> <td> <?= $location->created->format(DATE_RFC850) ?> </td> </tr> <?php endforeach; ?> </table>
Is it that its not possible to use Lazy Load between databases or is it the unconvetional table name that makes things difficult?