📜 ⬆️ ⬇️

Work with PGPool + ORM Yii2

Today there will be a small “hack” for ORM Yii2 if you use PGPool.
Yes, these are again some crutches (as in my first article), but it seems to me that these (taking into account the victorious march of PostgreSQL) may be useful to even more people.

All those who work with PGPool in Master-Slave mode will sooner or later face the task of when to make selections without fail from the wizard. Fortunately, the developers took care of us and gave us this opportunity. Who saw the scheme of work of PGPool will understand me: we write a simple line / * NO LOAD BALANCE * / before the select and our PGpool request will be sent to the master database.

Problems begin when we need to use ORM.

On the example of Yii2, we have so far decided this:
')
Overriding the ActiveQuery class and, most importantly, its createCommand () method

class ActiveQuery extends \yii\db\ActiveQuery { private $_noLoadBalance = false; /** *     ,     * * @return $this */ public function noBalance() { $this->_noLoadBalance = true; return $this; } /** * @inheritdoc */ public function createCommand($db = null) { /* @var $modelClass ActiveRecord */ $modelClass = $this->modelClass; if ($db === null) { $db = $modelClass::getDb(); } if ($this->sql === null) { list ($sql, $params) = $db->getQueryBuilder()->build($this); } else { $sql = $this->sql; $params = $this->params; } $comment = ''; if (true === $this->_noLoadBalance) { $comment = '/*NO LOAD BALANCE*/'; } return $db->createCommand($comment . $sql, $params); } } 


And we use it this way:

 $user = User::find()->where([ User::ATTR_ID => $userid, ]) ->noBalance() ->one(); 


And I really want the Yii developers to somehow somehow do it “inside” out of the box.

Source: https://habr.com/ru/post/307248/


All Articles