WeSee
WeSee

Reputation: 3762

Yii2 findBySql: How to specify $params?

Yii2 provides ActiveRecord::findBySql für raw SQL queries:

public static yii\db\ActiveQuery findBySql ( $sql, $params = [] )

Since there is no hint in the documentation: How to specify $params?

Upvotes: 0

Views: 2297

Answers (1)

Muhammad Omer Aslam
Muhammad Omer Aslam

Reputation: 23738

UPDATE

The reason there isn't any docs about the params passed to the findBySql() method is because the method returns the instance of ActiveQuery and if you see the last line of this method in yii\db\ActiveRecord.php it sets the $params via $query->params($params), means the yii\db\ActiveQuery function params($params) which defines the $params as

$params list of query parameter values indexed by parameter placeholders. For example, [':name' => 'Dan', ':age' => 31].


I guess you should try the following way if lets say you have a table with name product

+----+-----------------+------------+--------+
| id | name            | is_deleted | price  |
+----+-----------------+------------+--------+
|  1 | shugal          |          1 |  65.00 |
|  2 | spoon           |          1 |  55.00 |
|  4 | kettle          |          1 |  15.00 |
|  5 | spoon           |          0 |  15.00 |
|  6 | plates          |          0 | 105.00 |
|  7 | dishes          |          0 |  15.00 |
|  8 | forks           |          0 |  15.00 |
| 10 | pressure cooker |          0 | 203.00 |
| 16 | shugal          |          1 |  65.00 |
| 17 | something       |          0 |  25.00 |
| 25 | multi product   |          0 |   0.00 |
| 66 | pans            |          0 |  15.00 |
+----+-----------------+------------+--------+

using the following code you can select all the products that are deleted using params

$q = Product::findBySql(
    "SELECT * FROM product where is_deleted=:deleted",
    [':deleted' => 1]
)->all();

Hope this helps

Upvotes: 3

Related Questions