Yii2在控制器中过滤数据



我是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();

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

Yii::$app->response->format = yiiwebResponse::FORMAT_JSON;
return ['data' => $product];
}

相关内容

  • 没有找到相关文章

最新更新