2010-12-09 3 views
2

Zend Framework에서 multidb 패턴을 사용하고 있습니다.필터 Zend Framework의 SELECT 및 INSERT/UPDATE/DELETE 쿼리

일반적으로 나는 MysqlDB의 마스터/슬레이브 아키텍처를 사용하게 될 것입니다.

그래서 제 질문은 내가/슬레이브 데이터베이스 및 INSERT/UPDATE에서 SELECT 쿼리를 실행 마스터 데이터베이스에 쿼리를 삭제하려면해야 할 일이다

resources.multidb.primary.adapter = PDO_MYSQL 
resources.multidb.primary.host = localhost 
resources.multidb.primary.username = root 
resources.multidb.primary.password = 123456 
resources.multidb.primary.dbname = tubaah_zend 
resources.multidb.primary.default = true 

resources.multidb.secondary.adapter = PDO_MYSQL 
resources.multidb.secondary.host = localhost 
resources.multidb.secondary.username = root 
resources.multidb.secondary.password = 123456 
resources.multidb.secondary.dbname = tubaah 

그래서 내가 원하는처럼

내 application.ini 보인다 2 차 데이터베이스에서 모든 SELECT 조회를 실행하고 1 차 데이터베이스에서 모든 INSERT/UPDATE/DELETE를 실행하십시오.

답변

1

내가 작동합니다/삭제/업데이트를 삽입 믿고 잘, 즉 :

My_Model_DbTable_MyTable.php : 당신이 보조 데이터베이스를 사용하고자하는 경우

function myFunction() { 
    $this->insert() 
    $this->update() 
    $this->delete() 
} 

그러나, 당신이 사용하지 못할 수 있습니다 전형적인 $ this->을 선택() 메소드 :

My_Model_DbTable_MyTable.php

// Override getAdapter() function to be able to obtain secondary database 
function getAdapter($name = 'primary') { 
    $resource = $this->getPluginResource('multidb'); 
    $resource->init(); 

    // Ensure only primary and secondary are allowed 
    if ($name == 'secondary' || $name == 'primary') { 
     return $resource->getDb($name); 
    } else { 
     return $this->_db; 
    } 
} 

function selectFromSecondary() { 
    $db = $this->getAdapter('secondary'); 
    $select = $this->select(true); 
    return $db->fetchAll($select); // normally this is $this->fetchAll() 
} 

위와 같이 getAdapter()를 오버라이드하여 기본 데이터베이스에 액세스하는 경우에는 변경할 필요가 없지만 보조 어댑터가 필요한 경우 $ this-> getAdapter()를 통해 보조 어댑터를 가져와야합니다. 보조 '라고 함)를 $ db와 같은 변수에 저장 한 다음 $ db 객체를 사용하여 select/insert/update/delete 메소드를 호출합니다.

수정 위의 코드를 약간 수정. getAdapter()에 대해서는 $ this -> _ db를 사용하고, fetch(), update(), insert(), delete() 등의 경우 $ db->를 $ this->).

1
function getAdapter($name = 'primary') { 
    $resource = $this->getPluginResource('multidb'); 
    $resource->init(); 

    // Ensure only primary and secondary are allowed 
    if ($name == 'secondary' || $name == 'primary') { 
     return $resource->getDb($name); 
    } else { 
     return $this->_db; 
    } 
} 

function selectFromSecondary() { 
    $db = $this->getAdapter('secondary'); 
    $select = $this->select(true); 
    return $db->fetchAll($select); // normally this is $this->fetchAll() 
} 
+0

답변을 주셔서 감사합니다. 간단히 말해서 MySql 쿼리가 실행되기 전에 실행되는 중앙 집중식 함수가 필요하며 쿼리의 유형에 따라 런타임에 연결이 변경됩니다. 즉, 쿼리가 선택되어 db-2에서 실행되고 쿼리가 삽입, 업데이트 또는 삭제 인 경우 그런 다음 db-1에서 실행하십시오. 잘만되면 나는 분명하다. –

관련 문제