我想使用 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 语句和返回的数据。采集日期、最新编辑、状态不合格的记录。
最佳答案
您制作 SELECT *
- 从所有指定的表中选择所有列。在您的表格中,某些字段具有相同的名称('acquisition_date'、'latest_edit'、'status' - 在'phones'和'workstations'中)。因此,你有一个不可预测的结果。也许,phpmyadmin 和 Codeigniter 使用不同的驱动程序。无论如何,仅使用 SELECT *
是非常不可靠的。
有两种解决方案:
- 代替
$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
...
- 或重命名字段,以免名称重复。
我推荐第一种方案。
关于php - Codeigniter 从数据库返回 Null 一个不为 null 的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57090859/