如何在yii2中为“查询”构建器设置连接?

时间:2014-09-23 11:23:25

标签: yii2

我想使用QueryBuilder:

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

使用非默认连接:

\Yii::$app->get('db_mysql')

我该如何正确地做到这一点?

2 个答案:

答案 0 :(得分:4)

使用:

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

当然,您必须在配置中设置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);
}

答案 1 :(得分:0)

在您的模型中创建方法

/**
 * @return \yii\db\Connection the database connection used by this AR class.
 */
public static function getDb()
{
    return Yii::$app->get('db_mysql');
}

之后

$rows = (new \yii\db\Query())
    ->select('id, name')
    ->from('user')
    ->limit(10)
    ->all(YourModel::getDb());

$rows = (new \yii\db\Query())
    ->select('id, name')
    ->from('user')
    ->limit(10)
    ->all(static::getDb());
在YourModel上下文中