Is there a safe way to generate conditional clause for Yii2 ORM with query string parameters? For example, we require a list of some food products, filtering by their properties:
GET /food/?weight[>]=1000&calories=[<]=200
And there is a plenty of different properties of the products: weight, calories, quantity, price.
I expect that it's possible to write something like (simplified code):
$query = new \yii\db\Query();
foreach ($_GET as $parameter => $condition){
foreach ($condition as $operator => $value){
$query->where(new SimpleCondition($parameter, $operator, $value));
}
}
But I doubt this approach is safe.
So, there are three questions:
- How is it possible to define the properties from url safely? Can we sanitize the query string parameter names (not values) before using in
ActiveQuery::where
clause? - What's the way to properly define operators like
IN, AND, OR, >, <, >=, <=, etc.
? - Is there any native Yii2 component for filtering or should I use a third-party module?