php - Codeigniter 从数据库返回 Null 一个不为 null 的字段

标签 php mysql codeigniter

我想使用 Codeigniter 从我的数据库返回一些数据。该查询是所有相关表的连接。 这是图表: enter image description here

来自模型的连接查询:

public function combine_all_data_related($hostname){
        $this->db->select('*');
        $this->db->from('workstations w');
        $this->db->join('occupations o', 'w.occupation_id = o.occupation_id', 'left');
        $this->db->join('departments d', 'd.department_id = o.department_id', 'left');
        $this->db->join('workstation_configuration wc', 'wc.service_tag = w.service_tag', 'left');
        $this->db->join('workstation_models wm', 'wm.workstation_model_id = wc.workstation_model_id', 'left');
        $this->db->join('workstation_types wt', 'wt.workstation_type_id = wm.workstation_type_id', 'left');
        $this->db->join('users u', 'u.occupation_id = o.occupation_id', 'left');
        $this->db->join('phone_numbers pn', 'pn.fmid = u.fmid', 'left');
        $this->db->join('phones p', 'p.phone_number_id = pn.phone_number_id', 'left');
        $this->db->join('phone_brands pb', 'pb.phone_brand_id = p.phone_brand_id', 'left');
        $this->db->where("w.hostname = '" . $hostname . "'");

        $query = $this->db->get();

        return $return = $query->result();
    }

在数据库中,我有这条记录: enter image description here

在浏览器中,这里是 var_dumps 结果 SQL 语句和返回的数据。采集日期、最新编辑、状态不合格的记录。

enter image description here

最佳答案

您制作 SELECT * - 从所有指定的表中选择所有列。在您的表格中,某些字段具有相同的名称('acquisition_date'、'latest_edit'、'status' - 在'phones'和'workstations'中)。因此,你有一个不可预测的结果。也许,phpmyadmin 和 Codeigniter 使用不同的驱动程序。无论如何,仅使用 SELECT * 是非常不可靠的。

有两种解决方案:

  1. 代替 $this->db->select('*'); 使用 $this->db->select('明确列出所有需要的字段', NULL);

例如:

$this->db->select('w.hostname ..., w.acquisition_date AS ws_acquisition_date ..., o.occupation_id ..., p.acquisition_date AS ph_acquisition_date ...', NULL);

或者至少对于请求中的同名字段明确指定名称别名:

$this->db->select('*, w.acquisition_date AS ws_acquisition_date, p.acquisition_date AS ph_acquisition_date, w.status AS ws_status, w.latest_edit AS ws_latest_edit, p.latest_edit AS ph_latest_edit', NULL);

在 PHP 中,将这些字段称为:

$return->ws_acquisition_date
$return->ph_acquisition_date
$return->ws_status
...
  1. 或重命名字段,以免名称重复。

我推荐第一种方案。

关于php - Codeigniter 从数据库返回 Null 一个不为 null 的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57090859/

相关文章:

php - 将 3 小时添加到 php 中 new Cassandra\Timestamp() 生成的时间戳中

javascript - 如何修复此代码 : Output gives an error

ubuntu - nginx + passenger + phpmyadmin = 拒绝访问

php函数返回结果集

mysql - 直接从 iPad 应用程序连接到 MySQL(不通过 PHP 等)

php - MySQL 和 CI 的 UTF8 数据问题

php - 在 PHP 中正确使用 isset 和 filter_input

mysql - 将 MySQL 表分成 2 个?当前搜索速度太慢

php - 计算用户当前钱包余额的最佳方法是什么?

php - 如何在codeigniter中获取IP地址?