2014-07-10 64 views
0

我在一個模塊/模型文件夾中有模型,名爲SuperModel。並在另一個模塊/模型文件夾中關聯ChildModel1,ChildModel2。yii來自另一個數據庫的活動記錄相關記錄

來自database1的超級模型數據記錄必須包含放置在其他數據庫中的相關記錄Child1和Child2。

有沒有辦法通過yii ActiveRecord關係機制同時通過少數數據庫獲取關係記錄?類似的東西:

$super_record = SuperRecordModel::model()->with( 
    'RecordFromDB_A', 
    'RecordFromDB_B' 
)->findAll($criteria); 

或者我需要使用類似:

// From first DB... 
$super_record = SuperRecordModel::model()->findAll(); 

// Separately from another DB A... 
$super_record->ChildsA = ChildsAModel::model()->findAll(
    't.parent_id = :super_record_id' 
); 

// Separately from another DB B... 
$super_record->ChildsB = ChildsBModel::model()->findAll( 
    't.parent_id = :super_record_id' 
); 

怎樣是正確的?

更新:我不能在多數據庫選擇操作中使用yii活動記錄關係...如何在活動記錄方法內的數據庫之間切換?例如:

$catalogs = $this->findAll(); 

// Set new database connection for this context.. 
// $this->setDbConnection(yii::app()->db2); 

foreach($catalogs as &$catalog) { 
    $catalog->service = Services::model()->find(
     't.catalog_id = :catalog_id', ...); 
    // this gives error: table services cannot be found in the database 
} 
+1

您是否測試過兩種方法,看它是否有效?我沒有yii設置來測試。我在yii中發現了關於多重數據庫的支持.... http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/ – xJoshWalker

+0

謝謝@joshjwalker,我讀過這個文檔,現在瞭解我需要實現代碼的第二個變體...如何在活動記錄方法內的數據庫之間切換? – itnelo

+0

在您的「服務」ActiveRecord模型中,您需要定義備用數據庫連接,類似於我發送的文章的「GetDbConnection()覆蓋」部分。這將是我最好的猜測 – xJoshWalker

回答

0

Okey,我探討了文檔,評論和現在這個問題已經解決。

一個數據庫中的表不能直接引用另一個 數據庫中的表,這意味着關係不會跨越數據庫邊界。

http://www.yiiframework.com/wiki/123/multiple-database-support-in-yii/

解決方案。讓我們爲將來使用模塊的所有數據庫連接寫入設置參數。例如:

'modules' => array(
    'module_name' => array(
     'db1' => array(
      'class' => 'CDbConnection', 
      'connectionString' => 'mysql:host=...;dbname=db1', 
      'username' => 'user', 
      'password' => 'password', 
      'charset' => 'utf8', 
     ), 
     'db2' => array(
      'class' => 'CDbConnection', 
      'connectionString' => 'mysql:host=...;dbname=db2', 
      'username' => 'user', 
      'password' => 'password', 
      'charset' => 'utf8', 
     ), 
    ) 
), 

... 

在模塊的init()方法,或者你需要創建一個CDbConnection類的對象另一個邏輯的切入點,這是類似的東西:

$db1_connection = Yii::createComponent(Yii::app()->controller->module->db1); 
$db2_connection = Yii::createComponent(Yii::app()->controller->module->db2); 

然後用CDbConnection::createCommand擺脫數據庫所需的數據。

// Records from db1. 
$parent_records = $db1_connection 
    ->createCommand('SELECT * FROM parent_table') 
    ->queryAll(); 

// Records from db2 as childs of parent record. 
foreach($parent_records as &$parent_record) { 
    $parent_record['childs'] = $db2_connection 
     ->createCommand('SELECT * FROM child_table WHERE parent_id = :parent_id') 
     ->bindParam(':parent_id', $parent_record['parent_id']) 
     ->queryAll(); 
} 
+1

請注意,Yii 2.0支持不同數據庫中的表之間的關係。 http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#cross-database-relations – MrD

相關問題