我想使用QueryBuilder:
$rows = (new \yii\db\Query())
->select('id, name')
->from('user')
->limit(10)
->all();
使用非默认连接:
\Yii::$app->get('db_mysql')
我该如何正确地做到这一点?
答案 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上下文中