0

In CakePHP 2, find() would return data from related models in different databases, so long as I had set $useDbConfig appropriately in each Model file. Eg:

class Project extends AppModel {    
  public $useDbConfig = 'db1';

  public $belongsTo = array(
      'Client'
  );
}

class Client extends AppModel { 
  public $useDbConfig = 'db2';
}

//in controller:
$this->Project->find('first'); //will get Client data

In CakePHP 3, I've set up my Table Model files with defaultConnectionName(), and in my controller I'm using get() with 'contain' to fetch related models, but one of my related tables is in a different database. Where CakePHP 2 would seemingly issue a separate query to get this data, looks like Cake 3 tries to join the table, and that fails with "Undefined table: relation does not exist."

class ProjectsTable extends Table { 
  public static function defaultConnectionName() {
    return 'db1';
  }
  public function initialize(array $config){
    $this->addAssociations([
      'belongsTo' => [
        'Clients'
       ]
    ]);
  } 
}

class ClientsTable extends Table {  
  public static function defaultConnectionName() {
    return 'db2';
  }
}

//in controller:
$this->Projects->get($id,[
  'contain' => [
    'Clients'
  ]
]); //issues error that 'clients' relation does not exist

If I use get() on the related model directly, it works fine - so defaultConnectionName() is good, but does Cake ignore it when the model is being queried as a contained relation? Or how do I need to approach this differently?

EDIT: A solution to my problem came in a later version of CakePHP 3.x: Changing Fetching Strategies. Setting 'strategy' => 'select' on the association for the other table makes the join work seamlessly again as it did in Cake 2.

sambaneko
  • 1
  • 2
  • Possible duplicate of [cakePHP 3 - using different datascources in a Query](http://stackoverflow.com/questions/32033558/cakephp-3-using-different-datascources-in-a-query) – ndm Oct 14 '15 at 18:39
  • The database in this case is Postgres, so the solution there doesn't immediately work for me. I guess I'm also just curious why this worked in Cake 2 and wouldn't be accounted for in Cake 3 - is there a way to make it work like Cake 2 does it, without using a cross-db join? – sambaneko Oct 14 '15 at 18:44
  • Well, the new ORM wants to be more efficient, so it prefers joins over additional queries. Why it doesn't support a fallback similar to Cake 2.x, I don't know, you'll have to ask the core devs. A custom association class that uses additional queries might be an option for you. – ndm Oct 14 '15 at 19:05
  • Alright, thanks. I'm migrating an app from 2.x to 3.x, and was surprised when this no longer worked. A fallback would be nice. I'll take a look at adding custom queries in the meantime (or enabling cross-db joins for our Postgres db). – sambaneko Oct 14 '15 at 19:19

0 Answers0