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.
There is no CDbCriteria
concept in Yii2
anymore. Instead you can refer to the following classes:
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
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With