Select 在 codeigniter 中加入两列

Select Join for two columns in codeigniter

大家好;

Table 1
    id product_name location added_by updated_by added date
    1  LENOVO       St 23    2        1          2016-08-26

Table 2
id first_name last_name email
1  John       Doe       jd@email.com
2  Peter      Smith     ps@email.com

我想知道如何 select 使用 codeigniter 查询数据以获得这样的结果

product_name location added_by    updated_by
LENOVO       St 23    Peter Smith John Doe

我尝试过连接,但 added_by 列和 updated_by 列显示相同的数据。

这应该有效

$this->db->select('*')
  ->from('Table 1')
  ->join('Table 2', 'Table 2.id = Table 1.added_by', 'left')
  ->join('Table 2', 'Table 2.id = Table 1.updated_by', 'left');

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

return $query->result();

让我知道它是否有效。

您可以使用此查询来解决您的问题:

$this->db->select('t1.product_name,t1.location, CONCAT(t2_1.first_name, " ", t2_1.last_name) AS added_by, CONCAT(t2_2.first_name, " ", t2_2.last_name) AS updated_by'); 
$this->db->from('Table 1 t1');
$this->db->join('Table 2 t2_1', 't2_1.id = t1.added_by', 'left'); 
$this->db->join('Table 2 t2_2', 't2_2.id = t1.updated_by', 'left'); 
$query = $this->db->get();
return $query->result();

您可以根据查询中的 table 名称进行更改 Table 1Table 2