Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6568139
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T14:26:29+00:00 2026-05-25T14:26:29+00:00

All my reads should go to one DB connection All my writes should go

  • 0

All my reads should go to one DB connection
All my writes should go to another connection

How do I accomplish this in Yii, with minimal changing the code of the core library?

And on occasions (as stated in the comments) I will need the ability to control each Model type of connection, so read can go to the Master too.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T14:26:29+00:00Added an answer on May 25, 2026 at 2:26 pm

    I have written an app where the master admin panel could be used to create and administer several customer-facing “instances”, so there was the need to “direct” queries running inside the master app to any one of the instance-specific databases. I ‘ll illustrate a trimmed-down version what I did first (which is not as demanding as your goal) and present a more powerful approach afterwards.

    Using multiple databases for all queries

    Directing queries to a database that has been specified from beforehand is easy: just override the CActiveRecord::getDbConnection method. What I did can be trimmed down to this:

    abstract class InstanceActiveRecord extends CActiveRecord {
        public static $dbConnection = null;
    
        public function getDbConnection() {
            if (self::$dbConnection === null) {
                throw new CException('Database connection must be defined to work with instance records.');
            }
    
            return self::$dbConnection;
        }
    }
    

    So if you want to direct all operations to a specific database you simply have to derive your ActiveRecord models from InstanceActiveRecord instead of CActiveRecord, then just do InstanceActiveRecord::dbConnection = $connection and you are good to go.

    Using multiple databases with auto-selection based on query type

    For this you need to go deeper into CActiveRecord. It turns out that getDbConnection is mostly used by getCommandBuilder, which in turn is the method called by all the delete/update/insert families. So we need to pass some kind of context from those functions down to getDbConnection, where the choice of which connection we want to use will be made.

    For this we ‘re going to have to override all methods in those families, so a reasonable approach might be:

    Step 1. Add an optional parameter to getDbConnection and override it to return whichever connection you want it to based on the parameter value. The simplest would be something like this:

    public function getDbConnection($writeContext = null) {
        if ($writeContext === null) {
            return parent::getDbConnection(); // to make sure nothing will ever break
        }
    
        // You need to get the values for $writeDb and $readDb in here somehow,
        // but this can be as trivially easy as you like (e.g. public static prop)
        return $writeContext ? $writeDb : $readDb;
    }
    

    Step 2. Add an optional parameter to getCommandBuilder with the same semantics and override it to forward the value:

    public function getCommandBuilder($writeContext = null) {
        return $this->getDbConnection($writeContext)->getSchema()->getCommandBuilder();
    }
    

    Step 3. Find all call sites of getCommandBuilder (there will be a bunch of those) and getDbConnection (there were just 2 more than the one inside getCommandBuilder at the time I looked) and override them to specify the read/write context appropriately. Example:

    public function deleteAll($condition='',$params=array()) {
        Yii::trace(get_class($this).'.deleteAll()','system.db.ar.CActiveRecord');
    
        // Just need to add the (true) value here to specify write context:
        $builder=$this->getCommandBuilder(true);
        $criteria=$builder->createCriteria($condition,$params);
        $command=$builder->createDeleteCommand($this->getTableSchema(),$criteria);
        return $command->execute();
    }
    

    After this you should be ready to go. There’s also nothing stopping you from making a more involved context selection mechanism than the true/false option illustrated here, the concept is the same.

    Practical concerns

    While all of this will achieve the stated goal perfectly, there remains a question regarding the maintainability of this approach.

    It’s true that going this route will involve lots of copy/pasted code from CActiveRecord, which is not ideal if there’s the chance of moving your app to a later version of the framework later on; to do so, you will be forced to bring your subclass up to sync with the latest version of CActiveRecord.

    To migitate this and make your life easier in the future, you can consider this approach:

    1. Instead of copy/pasting and overriding only part of CActiveRecord, make an exact copy (minus the properties of course) of CActiveRecord and perform the changes there. In other words, copy over even those methods that you do not intend to override.
    2. Perform the changes mentioned above. Remember that this involves an override of getDbConnection and only really minor edits to a dozen or two of other places.
    3. Make your models extend the resulting class.

    Now when the time comes to upgrade to a later Yii version, you will need to bring your class in sync with CActiveRecord again. Fire up your favorite diff tool and compare your class with the target version of CActiveRecord. The diff tool will show you only the getDbConnection and minor edits, plus whatever changes were made to CActiveRecord in Yii’s core. Copy those other changes over to your class. Problem solved in 5 minutes tops.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I got a little problem, I got a code, that reads all pixels and
I read all of Microsoft's documentation but their claim is that it should work
The following line in my C program should provided All/Group/Owner read and write permissions
I should really be able to read a regexp by now, but all the
I have a map that reads an XML file; it's all very simple and
I build a website, that: reads data from a website by HttpWebRequest Sort all
I read all topics related to this question in stackoverflow and whole internet and
In this scenario there are two database servers: one is in our LAN (Server
I want to get all the image_name values from one of my tables where
With a RESTful service you can create, read, update, and delete resources. This all

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.