如何检查 CodeIgniter 模型查询是否返回数据?

问题描述 投票:0回答:1

我想验证数据库查询是否正确执行并返回预期的数据。

我的专业化模型.php

<?php
defined('BASEPATH') or exit('No direct script access allowed');
class SpecializationModel extends Hirer_Model
{
    public function __construct()
    {
        parent::__construct();
    }
    public function getTop10Specializations($dateFrom, $dateTo)
    {
        $subQuery = "(
        SELECT 
            applicant_id, 
            jobspec_id,
            @rn := CASE WHEN @var_applicant_id = applicant_id THEN @rn + 1 ELSE 1 END AS rn,
            @var_applicant_id := applicant_id 
        FROM (
            SELECT @var_applicant_id := NULL, @rn := NULL
        ) vars,
        applicant_jobpref 
        ORDER BY applicant_id, jobspec_id DESC
    )";

        $this->db
            ->select('spec.name, COUNT(sub_table.jobspec_id) AS total')
            ->from("$subQuery AS sub_table", false)
            ->join('applicant_personal personal', 'personal.id = sub_table.applicant_id', 'inner')
            ->join('job_specialization spec', 'sub_table.jobspec_id = spec.id', 'inner')
            ->where('sub_table.rn <=', 2)
            ->where('personal.registration_date >=', $dateFrom)
            ->where('personal.registration_date <=', $dateTo)
            ->group_by(['sub_table.jobspec_id', 'spec.name'])
            ->order_by('total', 'DESC')
            ->limit(10);

        $query = $this->db->get();
        log_message('debug', 'SQL Query: ' . $this->db->last_query());

        print_r($query->result_array());

        return $query->result_array();
    }
}

我尝试使用 Specialization.php 控制器

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Specialization extends Hirer_Controller
{
    public function __construct()
    {
        parent::__construct();

        $this->lang->load(
            dir_hirer($this->currentClass),
            $this->currentLanguage
        );

        $this->load->model(model_hirer('Specialization'), 'specialization');

        $this->addCustomCss(url_assets_css($this->currentClass));
    }

    public function index()
    {
        $dateFrom = '2019-07-01';
        $dateTo = '2023-06-30';

        $specializations = $this->specialization->getTop10Specializations($dateFrom, $dateTo);

        $xValuesJobs = [];
        $yValuesJobs = [];

        foreach ($specializations as $specialization) {
            $xValuesJobs[] = $specialization['name'];
            $yValuesJobs[] = $specialization['total'];
        }

        // JSON encode the data *before* sending it to the view
        $data = [
            'xValuesJobs' => json_encode($xValuesJobs),
            'yValuesJobs' => json_encode($yValuesJobs),
        ];
        // Load page components
        $this->loadHeader();  // Load the header
        if (!empty($xValuesJobs) && !empty($yValuesJobs)) {
            $this->loadContent('graph', $data); // Load graph view with data
        } else {
            // Optional: Load a fallback or message when there's no data
            $this->loadContent('no_data_message', ['message' => 'No data available for the selected period.']);
        }
        $this->loadFooter();  // Load the footer
    }
}

我试图在此视图中显示查询结果

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.js"></script>

    <div class="col-md-12 card p-2 my-3">
        <canvas id="myChart2" style="width:100%; height:350px;"></canvas>
    </div>

    <script>
        document.addEventListener("DOMContentLoaded", function () {

            const yLabels = ["Top 1", "Top 2", "Top 3", "Top 4", "Top 5", "Top 6", "Top 7", "Top 8", "Top 9", "Top 10"];

            const xValuesJobs = [];
            const yValuesJobs = [];
            const barColorsJobs = xValuesJobs.map(() => "#FF8A00");

            new Chart(document.getElementById("myChart2"), {
                type: "bar",
                data: {
                    labels: xValuesJobs,
                    datasets: [{
                        backgroundColor: barColorsJobs,
                        data: yValuesJobs
                    }]
                },
                options: {
                    legend: { display: false },
                    title: {
                        display: true,
                        text: "Top 10 Preferred Specializations"
                    },
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true,
                                callback: function (value) {
                                    return yLabels[10 - value] || "";
                                },
                                stepSize: 1,
                                max: 10
                            }
                        }]
                    }
                }
            });
        });
    </script>

没有错误,只是我的视图或图形变成白色空白,只显示背景,yLabels不会被渲染,我希望这是因为查询,但我如何检查它是否真的有效?

查询在原始 SQL 中工作,但在这种情况下,我将其转移到代码点火器查询生成器中,我还没有为此创建任何路由,因为这个视图就像我们当前仪表板内的卡片类型,这只是需要显示带有新数据的新模式,我是否还需要在仪表板的路径中配置某些内容,而不仅仅是只关注此 MVC?这个视图是一个模式,可以在租车者/主页中看到,我没有添加任何新路线,因为它已经在租车者/主页中呈现。

我使用

print_r($query->result_array())
log_message()
进行调试,但是我在哪里可以看到这个?我只知道 echo 然后它将显示在视图中,在这种情况下我仍然没有视图或控制器,-我在浏览器中没有看到任何输出”或“日志文件没有显示查询。

查询在原始 SQL 中工作,但在这种情况下,我将其转移到代码点火器查询生成器中,我还没有为此创建任何路由,因为这个视图就像我们当前仪表板内的卡片类型,这只是需要显示一个带有新数据的新模式,我是否还需要在仪表板的路径中配置一些东西,而不仅仅是只关注这个 MVC?这个视图是一个模式,可以在租车者/主页中看到,我没有添加任何新路线,因为它已经在租车者/主页中呈现。

php codeigniter
1个回答
0
投票

确保在

application/config/config.php
中启用日志记录,并使用
$config['log_threshold'] = 4;

可以使用

print_r($query->result_array())
直接打印查询结果

public function getTop10Specializations($dateFrom, $dateTo)
{ ....
    log_message('debug', 'SQL Query: ' . $this->db->last_query()); 
    print_r($query->result_array()); 
    return $query->result_array(); 
}

检查你的控制器(

Specialization
)是否将查询结果传递给视图

public function index()
{
    $dateFrom = '2019-07-01';
    $dateTo = '2023-06-30';

    $specializations = $this->specialization->getTop10Specializations($dateFrom, $dateTo);

    if (empty($specializations)) {
        echo 'No data available for the selected period.';
        return; // Prevent rendering a blank graph
    }

    echo '<pre>'; 
    print_r($specializations); // Output the data
    echo '</pre>';

    $xValuesJobs = [];
    $yValuesJobs = [];

    foreach ($specializations as $specialization) {
        $xValuesJobs[] = $specialization['name'];
        $yValuesJobs[] = $specialization['total'];
    }

    // Verify data before sending to the view
    var_dump($xValuesJobs, $yValuesJobs);

    // JSON encode the data properly for the view
    $data = [
        'xValuesJobs' => json_encode($xValuesJobs),
        'yValuesJobs' => json_encode($yValuesJobs),
    ];

    $this->loadHeader();
    $this->loadContent('graph', $data);
    $this->loadFooter();
}

看起来您的图表的问题是

xValuesJobs
yValuesJobs
数据未正确传递到图表。使用

const xValuesJobs = <?= $xValuesJobs; ?>; 
const yValuesJobs = <?= $yValuesJobs; ?>;
© www.soinside.com 2019 - 2024. All rights reserved.