Yii2 在控制器中过滤数据

发布于 2025-01-09 04:00:14 字数 568 浏览 0 评论 0原文

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

我该如何处理?

I'm new to YII framework, I want to filter my data on the frontend using product, month and year dropdown.
Here is what I have in my controller

<?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);
?>

How do I approach this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

℉絮湮 2025-01-16 04:00:14

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

<?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 响应 被 Yii 完全支持,包括数组转换:

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

First, make your query parameter part of the function definition:

<?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();

Second, JSON responses are fully supported by Yii including array conversion:

    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
     return ['data' => $product];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文