Mysql
 sql >> Datenbank >  >> RDS >> Mysql

So verwenden Sie mehrere Datenbanken dynamisch für ein Modell in CakePHP

Dieser Herr (Olivier ) hatte das gleiche Problem! (Vor einem Jahr) Er schrieb eine kleine Anpassung für den Controller s! Es ist ziemlich klein und es stellt sich heraus, dass es in 1.3 funktioniert und 2.x .

Jedenfalls ist dies meine endgültige Lösung, die ich in die app/Model/AppModel.php eingefügt habe :

class AppModel extends Model
{
  /**
   * Connects to specified database
   *
   * @param String name of different database to connect with.
   * @param String name of existing datasource
   * @return boolean true on success, false on failure
   * @access public
   */
    public function setDatabase($database, $datasource = 'default')
    {
      $nds = $datasource . '_' . $database;      
      $db  = &ConnectionManager::getDataSource($datasource);

      $db->setConfig(array(
        'name'       => $nds,
        'database'   => $database,
        'persistent' => false
      ));

      if ( $ds = ConnectionManager::create($nds, $db->config) ) {
        $this->useDbConfig  = $nds;
        $this->cacheQueries = false;
        return true;
      }

      return false;
    }
}

Und so habe ich es in meiner app/Controller/CarsController.php verwendet :

class CarsController extends AppController
{
  public function index()
  {
    $this->Car->setDatabase('cake_sandbox_client3');

    $cars = $this->Car->find('all');

    $this->set('cars', $cars);
  }

}

Ich wette, ich bin nicht der Erste oder Letzte mit diesem Problem. Ich hoffe also wirklich, dass diese Informationen Menschen und die CakePHP-Community finden werden.