Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 merge queries like cdbcriteria in yii1

Tags:

mysql

yii2

I have a problem regarding merge of multiple queries. In Yii 1.x you could merge a CDbCriteria with

$criteria->merge($otherCriteria)

How can I achieve the same nested conditions etc with queries in Yii2?

Edit: Let's say I want separate queries to form subqueries. And after all subqueries are done I want to merge them together to the one big query.

like image 708
Faenor Avatar asked Jan 09 '23 08:01

Faenor


2 Answers

There is no CDbCriteria concept in Yii2 anymore. Instead you can refer to the following classes:

  • http://www.yiiframework.com/doc-2.0/yii-db-query.html (yii\db\Query)
  • http://www.yiiframework.com/doc-2.0/yii-db-activequery.html (yii\db\ActiveQuery)

All you did before with CDbCriteria now you can do with above classes. So, there will be no need to merge two criteria with each other.

update

Yii2 also supports sub-queries like below (as Yii2's official guide):

$subQuery = (new Query)->select('COUNT(*)')->from('user');
$query = (new Query)->select(['id', 'count' => $subQuery])->from('post');

Which results in:

SELECT `id`, (SELECT COUNT(*) FROM `user`) AS `count` FROM `post`

http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html#building-query

like image 73
Ali MasudianPour Avatar answered Jan 11 '23 20:01

Ali MasudianPour


I also recently ran into this issue. Complete fusion of queries (select, join etc.) does not exist (as I understand it). But you can manually merge conditions, for example:

    $query1 = \app\models\User::find()
        ->where(['column1' => 'value1', 'column2' => 'value2']);

    $query2 = \app\models\User::find()
        ->where(['and', '[[column3]] = :column3', '[[column4]] = :column4'])
        ->addParams([
            ':column3' => 'value3',
            ':column4' => 'value4'
        ]);

    // merge conditions
    $query1->orWhere($query2->where);
    $query1->addParams($query2->params);

    // build SQL
    echo $query1->createCommand()->rawSql;

Built SQL:

SELECT * FROM `yii2_user` WHERE 
    ((`column1`='value1') AND (`column2`='value2')) OR 
    ((`column3` = 'value3') AND (`column4` = 'value4'))
like image 35
IStranger Avatar answered Jan 11 '23 22:01

IStranger