关于yii2:yii2-读写分离模式下强制读主库

44次阅读

共计 929 个字符,预计需要花费 3 分钟才能阅读完成。

yii2 配置读写主动读写拆散时,在一些场景下可能须要强制读主库。以及 createCommandin 查问参数绑定实现办法。

强制读主库

yii2 配置读写主动主从拆散时,在一些场景下可能须要强制读主库。这时咱们能够应用 \yii\db\ConnectionuseMaster 办法来操作,该办法会将 enableSlaves 模式在本次查问会话中敞开,查问实现后继而复原。

/** @var $users User[] */
$users = User::getDb()->useMaster(function($db) use ($ids) {
    /** @var $db \yii\db\Connection */
    return $db->createCommand("SELECT * FROM" . User::tableName() . "where find_in_set(`id`, :ids) AND `is_del`=:is_del", [':ids' => implode(',', $ids),
        ':is_del' => Base::NOT_DELETED,
    ])->queryAll(\PDO::FETCH_OBJ);
});

createCommand IN 查问

createCommand 构建 sql 时可能会遇到 IN 查问的场景,yii2 貌似不反对,能够应用 find_in_set 来代替。

$db->createCommand("SELECT * FROM `users` WHERE `id` in(:ids)", [':ids' => [1, 2, 3]]);
$db->createCommand("SELECT * FROM `users` WHERE `id` in(:ids)", [':ids' => implode(",", [1, 2, 3])]);

会被解析成

SELECT * FROM `users` WHERE `id` in(1);
SELECT * FROM `users` WHERE `id` in('1,2,3');// 看到 '1,2,3' 果决换 find_in_set

可行用法

$db->createCommand("SELECT * FROM `users` WHERE find_in_set(`id`, :ids)", [':ids' => implode(",", [1, 2, 3])]);

正文完
 0