yii同一个控制器操作多个数据库表

main.php

        'db1'=>array(
            'class'=>'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=test1',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ),
        'db2'=>array(
            'class'=>'CDbConnection',
            'connectionString' => 'mysql:host=localhost;dbname=test',
            'emulatePrepare' => true,
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ),


建立数据库表:

Create a table named testpost in db1 as follows:

DROP TABLE IF EXISTS `testpost`;
CREATE TABLE IF NOT EXISTS `post` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `title` VARCHAR(255) NOT NULL,
    `text` TEXT NOT NULL,
    PRIMARY KEY  (`id`)
);

Create a table named test1comment in db2 as follows:

DROP TABLE IF EXISTS `test1comment`;
    CREATE TABLE IF NOT EXISTS `test1comment` (
    `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    `text` TEXT NOT NULL,
    `postId` INT(10) UNSIGNED NOT NULL,
    PRIMARY KEY  (`id`)
);

控制器DbController.php

<?php
class DbController extends Controller
{
    public function actionIndex()
    {

        $post = new Testpost();
        $post->title = "Post #".rand(1, 1000);
        $post->text = "text";
        $aa=$post->save();
        echo '<h1>Posts</h1>';
        
        $posts = Testpost::model()->findAll();
        foreach($posts as $post)
        {
            echo $post->title."<br />";
        }
        echo "<hr>";

        $comment = new Test1comment();
        $comment->postId = $post->id;
        $comment->text = "comment #".rand(1, 1000);
        $comment->save();
        
        echo '<h1>Comments</h1>';
        
        $comments = Test1comment::model()->findAll();
        foreach($comments as $comment)
        {
            echo $comment->text."<br />";
        }
    }
}


模型Testpost.php

<?php
class Testpost extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
    
//    public function tableName()
//    {
//        return 'testpost';
//    }
    public function getDbConnection()
    {
        return Yii::app()->db2;
    }
}


模型Test1comment.php

<?php
class Test1comment extends CActiveRecord
{
    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }
//    public function tableName()
//    {
//        return 'testpost';
//    }
    public function getDbConnection()
    {
        return Yii::app()->db1;
    }

}


然后执行控制器中的方法,即成功在一个控制器方法中操作两个数据库。

原文地址:https://www.cnblogs.com/jami918/p/3049565.html