我的项目中有一个 yii2 查询,例如$query=Car::find() ->andFilterWhere(['in','make_id',array_filter(explode(',', $this->makes))]) ->andFilterWhere(['in','model_id',array_filter(explode(',', $this->models))]) ->andFilterWhere(['>=', 'price', $this->price_start]) ->andFilterWhere(['<=', 'price', $this->price_end]) ->andFilterWhere(['>=', ModelYear::tableName().'.year', $this->year_start]) ->andFilterWhere(['<=', ModelYear::tableName().'.year', $this->year_end]) ->andFilterWhere(['>=', 'kilometer', $this->km_start]) ->andFilterWhere(['<=', 'kilometer', $this->km_end]) ->andFilterWhere(['like', 'title', $this->title])而且我还有另一个查询$command = $connection->createCommand("select A.id,A.make_eng,Count(B.make_id) from tbl_car_makes A,(**Can i use the first $query here**) as B where A.id=B.make_id group by A.id,A.make_eng");$data = $command->queryAll();我如何在指定位置的第二个查询中使用第一个查询
1 回答
繁花如伊
TA贡献2012条经验 获得超12个赞
你有两个选择如何做到这一点。
1)可能更好的选择是对第二个查询也使用查询构建器。
$query2 = (new \yii\db\Query())
->select(['A.id', 'A.make_eng', 'COUNT(B.make_id)')
->from(['A' => 'tbl_car_makes', 'B' => $query])
->where('A.id = B.make_id')
->groupBy(['A.id', 'A.make_eng']);
$data = $query2->all();
2) 另一种选择是将第一个查询转换为 SQL 字符串。这种方法的问题是您将不得不处理参数。
$queryCommand = $query->createCommand();
$querySql = $queryCommand->getSql();
$command = $connection->createCommand(
"select A.id,A.make_eng,Count(B.make_id) from tbl_car_makes A,($querySql) as B where A.id=B.make_id group by A.id,A.make_eng",
$queryCommand->params
);
$data = $command->queryAll();
- 1 回答
- 0 关注
- 82 浏览
添加回答
举报
0/150
提交
取消