Yii2 在控制器中过滤数据

Yii2 filter data in controller

我是 YII 框架的新手,我想使用产品、月份和年份下拉菜单在前端过滤我的数据。 这是我控制器中的内容

<?php
public function actionProducts()
    {
        $sql = "SELECT product, cost, supplier, month, year 
                FROM products
                WHERE year = :year
                GROUP BY product, month, year";
        $product = Data::findBySql($sql, [':year' => 2022])->asArray()->all();

        $response = ['data' => $product];
        header('Content-Type: application/json');
        return json_encode($response, JSON_NUMERIC_CHECK);
?>

我该如何处理?

首先,将查询参数作为函数定义的一部分:

<?php
public function actionProducts($product, $month, $year)
{
    $sql = "SELECT product, cost, supplier, month, year 
            FROM products
            WHERE year = :year AND month=:month AND year=:year
            GROUP BY product, month, year";
    $product = Data::findBySql($sql, [
        ':year' => $year, ':month'=>$month, ':product'=>$product
    ])->asArray()->all();

其次,JSON responses Yii 完全支持包括数组转换:

    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     return ['data' => $product];
}