How Can i use yii2 query along with the normal query

Abhi Jith :

I have a yii2 query in my project like

$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])

And also i have another query like

$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();

How can i use the first query inside the second query in the specified position

Michal Hynčica :

You have two options how to do that.

1) Probably the better option is to use the query builder for the second query too.

$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) Another option is to convert the first query to SQL string. The problem with this approach is that you will have to deal with params.

$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();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=401695&siteId=1