我在一个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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句