如何在yii2中设置查询生成器的连接?
问题描述:
我想使用的QueryBuilder:如何在yii2中设置查询生成器的连接?
$rows = (new \yii\db\Query())
->select('id, name')
->from('user')
->limit(10)
->all();
与非默认的连接:
\Yii::$app->get('db_mysql')
我怎样才能做到这正常吗?
答
用途:
$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
答
在模型建立方法
/**
* @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方面
您要设置新的连接 – Kshitiz 2014-09-23 11:23:59
我给你新的连接 – Kshitiz 2014-09-23 11:30:49