How to establish connection for Query builder in yii2?
2 answers
Using:
$rows = (new \yii\db\Query())
->select('id, name')
->from('user')
->limit(10)
->all(\Yii::$app->db_mysql);
Of course you need to set the component db_mysql
in your config
Doc:
/**
* 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);
}
+4
source to share
In the way of creating the model
/**
* @return \yii\db\Connection the database connection used by this AR class.
*/
public static function getDb()
{
return Yii::$app->get('db_mysql');
}
thereafter
$rows = (new \yii\db\Query())
->select('id, name')
->from('user')
->limit(10)
->all(YourModel::getDb());
or
$rows = (new \yii\db\Query())
->select('id, name')
->from('user')
->limit(10)
->all(static::getDb());
in the context of YourModel
0
source to share