如何在yii2中设置查询构建器的连接?

erc*_*ing 4 yii2

我想使用QueryBuilder:

$rows = (new \yii\db\Query())
    ->select('id, name')
    ->from('user')
    ->limit(10)
    ->all();
Run Code Online (Sandbox Code Playgroud)

使用非默认连接:

\Yii::$app->get('db_mysql')
Run Code Online (Sandbox Code Playgroud)

如何正确执行此操作?

Lar*_*i13 5

使用:

$rows = (new \yii\db\Query())
    ->select('id, name')
    ->from('user')
    ->limit(10)
    ->all(\Yii::$app->db_mysql);
Run Code Online (Sandbox Code Playgroud)

当然,您必须db_mysql在配置中设置组件

文件:

/**
 * Executes the query and returns all results as an array.
 * @param Connection $db the database connection used to generate the SQL statement.
 * If this parameter is not given, the `db` application component will be used.
 * @return array the query results. If the query results in nothing, an empty array will be returned.
 */
public function all($db = null)
{
    $rows = $this->createCommand($db)->queryAll();
    return $this->populate($rows);
}
Run Code Online (Sandbox Code Playgroud)