Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.