yii来自其他数据库的活动记录相关记录

时间:2014-07-10 12:49:12

标签: php yii

我在一个模块/模型文件夹中有名为SuperModel的模型。和相关的ChildModel1,ChildModel2在另一个模块/ models文件夹中。

来自database1的SuperModel数据记录必须包含相关记录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 个答案:

答案 0 :(得分: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();
}
相关问题