PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, February 27, 2022

[FIXED] How to set the connection of associated table in CakePHP

 February 27, 2022     cakephp, cakephp-3.0, php     No comments   

Issue

I actually have 2 databases, one named as clientDefaultDb and client1Db. here's the code of association.

ProductsController

    $connection = ConnectionManager::get('client1Db');
    $productSource = TableRegistry::get('Products', ['connection' => 
             $connection]);

    $products = $productSource->find('all');
    $products->contain(['ProductUnits']);

Here we set the connection of the table to Client1Db and I call the contain with ProductUnits

ProductTable.php

    public function initialize(array $config)
    {
        parent::initialize($config);

        $this->setTable('products');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');

        $this->addBehavior('Timestamp');

        $this->hasMany('ProductUnits')
            ->setForeignKey([
                'item_code'
            ])
            ->setBindingKey([
                'item_code'
            ]);

    }

The return is no error. It fetched the product correctly and have some data, but the problem is there's no data at ProductUnits it's empty.

I tried to manually query directly to the database it return something. Tried copying the data of ProductUnits at Client1Db then pasted it to the clientDefaultDb then I tried running the code again, and the ProductUnits return the data that i've been copied. so probably all associated table is difinetely connected to the default database. So how can I change the default connection of the associated tables?


Solution

I managed to make it work. Thanks @burzum for the idea.

here's the code.

$this->loadModel('ProductUnits'); 
$connection = ConnectionManager::get('client1Db'); 
$this->ProductUnits->setConnection($connection); 


Answered By - VLDCNDN
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing