0

I have an array of conditions for where() method, that can be successfully added to query builders:

 $condition = [
     'AND',
     ['archived' => 0],
     ['broken' => 0],
     ['gender' => 1],
     [
         'OR',
         ['visible' => 1],
         ['status' => 1],
     ],
 ];

but in some place I need to convert this array to string

(`archived` = 0) AND (`broken`= 0) AND (`gender` = 1) AND (`visible` = 1 OR `status` = 1)

and then place it to select() method like raw SQL statement

SUM(IF((`archived` = 0) AND (`broken`= 0) AND (`gender` = 1) AND (`visible` = 1 OR `status` = 1)))
2
  • Why do you need it to be a string, can't you use a subquery? Commented Nov 11, 2020 at 11:25
  • how can I insert query object inside of SUM(IF(...))? Commented Nov 11, 2020 at 14:35

1 Answer 1

1

You need to use buildCondition() and pass params to main query:

$sql = Yii::$app->db->queryBuilder->buildCondition($condition, $params);
$query
    ->select([
        'myField' => "SUM(IF($sql, 1, 0))"
    ])
    ->addParams($params);
Sign up to request clarification or add additional context in comments.

2 Comments

If the query is related to some ActiveRecord model it might be better to use its getDb() method instead of Yii::$app->db to make sure same connection component is used.
by the way we cannot put creating a definite string into separate method. It should be used only at once in method where we get data

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.