Skip to content

Instantly share code, notes, and snippets.

@oh-sky
Created December 14, 2013 01:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save oh-sky/7954728 to your computer and use it in GitHub Desktop.
Save oh-sky/7954728 to your computer and use it in GitHub Desktop.
CakePHP2で、特定のモデルでのSELECTでレプリケーションスレーブを参照する方法 AppModel::$useReplicaをtrueにすると、参照先がslaveになる belongsToのモデルもslaveからの参照となる
// app/Config/database.php
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'master.mysql.host',
'login' => 'mysql_username',
'password' => 'mysql_password',
'database' => 'schema_name',
'prefix' => '',
'encoding' => 'utf8',
);
public $replica = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'slave.mysql.host',
'login' => 'mysql_username',
'password' => 'mysql_password',
'database' => 'schema_name',
'prefix' => '',
'encoding' => 'utf8',
);
}
//-----------------
// app/Model/AppModel.php
class AppModel extends Model {
public $useReplica = false;
public function beforeFind($queryData) {
if ($this->useReplica) {
$this->useDbConfig = 'replica';
foreach ($this->belongsTo as $btModelName => $btModelData) {
$this->{$btModelName}->useDbConfig = 'replica';
}
}
return $queryData;
}
public function afterFind($results, $primary = false) {
if ($this->useReplica) {
$this->useDbConfig = 'default';
foreach ($this->belongsTo as $btModelName => $btModelData) {
$this->{$btModelName}->useDbConfig = 'default';
}
}
return $results;
}
}
//-----------------
// app/Model/Hoge.php
class Hoge extends AppModel {
public $useReplica = true;
public $belongsTo = array(
'Fuga',
'Foo',
'Bar',
);
}
//-----------------
// app/Controller/HogesController.php
class HogesController extends AppController {
public function index() {
$this->set('hoge', $this->Hoge->find('all'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment