【问题标题】:Codeigniter returns Null from database a field which is not nullCodeigniter 从数据库返回 Null 一个不为空的字段
【发布时间】:2019-07-18 09:05:52
【问题描述】:

我想用 Codeigniter 从我的数据库中返回一些数据。该查询是来自所有相关表的连接。 这是图表:

来自模型的连接查询:

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

在数据库中,我有这样的记录:

这里是浏览器中的 var_dumps 结果 SQL 语句和返回的数据。获取日期、最新编辑和状态不OK的记录。

【问题讨论】:

  • 试试这个 echo $this->db->last_query();在 $query 语句之后
  • 最后一张图片的第一段是 print_r($this->db->last_query());
  • 能否请您给出sql转储,以便我们识别
  • 工作站和电话表中有 aquisition_date 字段,因为电话表在查询的后面加入,它的值覆盖第一个,为这些字段提供不同的别名。
  • 请显示最后的 sql 转储。由于 LEFT JOIN,它可能为 null。

标签: php mysql codeigniter


【解决方案1】:

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

有两种解决方案:

  1. $this->db->select('explicitly list all need fields', NULL);代替$this->db->select('*');

例如:

$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. 或重命名字段,以免名称重复。

我推荐第一种解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2018-12-02
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 1970-01-01
    相关资源
    最近更新 更多