猿问

我如何将 yii2 查询与普通查询一起使用

我的项目中有一个 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();

我如何在指定位置的第二个查询中使用第一个查询


Cats萌萌
浏览 83回答 1
1回答

繁花如伊

你有两个选择如何做到这一点。1)可能更好的选择是对第二个查询也使用查询构建器。$query2 = (new \yii\db\Query())&nbsp; &nbsp; ->select(['A.id', 'A.make_eng', 'COUNT(B.make_id)')&nbsp; &nbsp; ->from(['A' => 'tbl_car_makes', 'B' => $query])&nbsp; &nbsp; ->where('A.id = B.make_id')&nbsp; &nbsp; ->groupBy(['A.id', 'A.make_eng']);$data = $query2->all();2) 另一种选择是将第一个查询转换为 SQL 字符串。这种方法的问题是您将不得不处理参数。$queryCommand = $query->createCommand();$querySql = $queryCommand->getSql();$command = $connection->createCommand(&nbsp; &nbsp; "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",&nbsp; &nbsp; $queryCommand->params);$data = $command->queryAll();
随时随地看视频慕课网APP
我要回答