douji9518 2015-08-10 18:58
浏览 82

Cakephp为整个项目切换数据库连接

How can I switch the database for the entire project like this example:

User 1 uses database test1

User 2 uses database test2

User 3 uses database test3

Like this above... Those ID from User, will come from the default database ( Login page )

PS: Sorry for my bad english, I need some more information, please tell me.

  • 写回答

1条回答 默认 最新

  • dongyou9818 2015-08-11 05:59
    关注

    Create multiple database configurations in database.php

    Let say we have default, test1, test2, test3 configurations.

    As you said user data is in default db config and I consider that you are using AUTH COMPONENT for authorization.

    Now add following function in AppController

    
        public function beforeFilter() {
            //call change db config function on user login and pass which config need to use
            if( $this->Auth->loggedIn() ) {
                //user login
                ///Some logic to select db config according login user.
                $dbConfig = "result of logic which return db config name";
                $this->_userSpecificDbConfig($dbConfig);
                }
        }
    
        private function _userSpecificDbConfig($dbConfig) {
            //get model name
            $model =  $this->name;
            //set db configuration for user
            switch($dbConfig) {
                case 'test1':
                    $this->{$model}->useDbConfig = "test1";
                    break;
                case 'test2':
                    $this->{$model}->useDbConfig = "test2";
                    break;
                case 'test3':
                    $this->{$model}->useDbConfig = "test3";
                    break;
                default: 
                    $this->{$model}->useDbConfig = "default";
            }
        }
    
    

    Try this code.

    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了