2014-09-23 53 views
3

我想使用的QueryBuilder:如何在yii2中設置查詢生成器的連接?

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

與非默認的連接:

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

我怎樣才能做到這正常嗎?

+0

您要設置新的連接 – Kshitiz 2014-09-23 11:23:59

+0

我給你新的連接 – Kshitiz 2014-09-23 11:30:49

回答

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); 
} 
+0

greaaaaaaat的解決方案!優秀的,這是我正在尋找,謝謝拉里 – Faradox 2015-08-10 07:27:00

0

在模型建立方法

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

AFTE [R是

$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方面

相關問題