繁体   English   中英

yii来自另一个数据库的活动记录相关记录

[英]yii active record related records from another databases

我在一个module / models文件夹中有一个名为SuperModel的模型。 和相关的ChildModel1,ChildModel2在另一个module / 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
}

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM