ActiveRecord使用读写分离,读的时候使用主库的问题

技术问题 · codeloving · 于 5年前 发布 · 2205 次阅读

配置了读写分离,但是特定的时候想读的时候也是读取主库,在使用ActiveRecord的情况下应该怎么使用?谢谢了

共收到 2 条回复
dakoo#15年前 0 个赞

我记得有这个的

对于事务里面的读,都是强制读主库

如果平常查询想读主库,yii是可以的,去看一下AR的源码

Fecmall#25年前 0 个赞

yii2的强制读某个库,看一下这个资料:https://github.com/yiisoft/yii2/issues/4799

https://github.com/yiisoft/yii2/blob/master/framework/db/Connection.php#L1054

/**
     * Executes the provided callback by using the master connection.
     *
     * This method is provided so that you can temporarily force using the master connection to perform
     * DB operations even if they are read queries. For example,
     *
     * ```php
     * $result = $db->useMaster(function ($db) {
     *     return $db->createCommand('SELECT * FROM user LIMIT 1')->queryOne();
     * });
     * ```
     *
     * @param callable $callback a PHP callable to be executed by this method. Its signature is
     * `function (Connection $db)`. Its return value will be returned by this method.
     * @return mixed the return value of the callback
     * @throws \Exception|\Throwable if there is any exception thrown from the callback
     */
    public function useMaster(callable $callback)
    {
        if ($this->enableSlaves) {
            $this->enableSlaves = false;
            try {
                $result = call_user_func($callback, $this);
            } catch (\Exception $e) {
                $this->enableSlaves = true;
                throw $e;
            } catch (\Throwable $e) {
                $this->enableSlaves = true;
                throw $e;
            }
            // TODO: use "finally" keyword when miminum required PHP version is >= 5.5
            $this->enableSlaves = true;
        } else {
            $result = call_user_func($callback, $this);
        }
        return $result;
    }
添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册
Your Site Analytics