【问题标题】:Join multiple left values with one right value用一个右值连接多个左值
【发布时间】:2015-12-07 13:37:41
【问题描述】:

在 Codeigniter 中,我尝试加入两个具有一对多关系的表。我想从我的表housetype 中得到一个结果,并从其他表housetype_member 中得到它的所有值/成员:

    $this->db->select('*');
    $this->db->join('housetype_member', 'housetype_member.housetype_id = housetype.PkId', 'left');
    $result = $this->db->get_where('housetype', array('PkId' => $id));

    return $result->result();

到目前为止,我得到了这样的结果:

array (size=2)
  0 => 
    object(stdClass)[28]
      public 'PkID' => string '4' (length=1)
      public 'Name' => string 'Classic' (length=7)
      public 'image' => string '1449063250.jpg' (length=14)
  1 => 
    object(stdClass)[30]
      public 'PkID' => string '4' (length=1)
      public 'Name' => string 'Classic' (length=7)
      public 'image' => string '1449063288.gif' (length=14)

前两个对象值(PkID、名称)来自第一个表,最后一个(图像)来自第二个左表。一切都很好,但是当我只需要一个 housetype 对象时,我得到了包含两个元素的数组。

有没有办法编写上面的代码,使我返回的对象看起来像这样:

object(stdClass)[28]
  public 'PkID' => string '4' (length=1)
  public 'Name' => string 'Classic' (length=7)
  public 'image' => 
    array (size=2)
      0 => string '1449063250.jpg' (length=14)
      1 => string '1449063288.gif' (length=14)

我需要第一个表中的一个结果,我想加入第二个表中的所有成员。

可以用 Codeigniters 活动记录来完成吗?

【问题讨论】:

  • 您可以通过MY_Model 实现此目的。
  • @Tpojka 我已经在使用 Bonfire 扩展的扩展模型,我不想在项目的后期切换它。 MY_Model 有一些有趣的功能

标签: php sql codeigniter join


【解决方案1】:

就您的第二个表具有该主键的多条记录而言,最好根本不使用联接。 您可以通过两次选择简单地获得它。

$this->db->select('PkID, name');
$this->db->where('PkId', $id);
$houseTypes = $this->db->get('housetype')->result();
foreach($houseTypes as $houseType){
    $this->db->select('image');
    $this->db->where('housetype_id', $houseType->PKId);
    $houseType->image = $this->db->get('housetype_member')->result();
}
return $houseTypes;

【讨论】:

  • 将 DB 查询操作放入 foreach 循环中是非常重要的。
猜你喜欢
  • 2011-12-21
  • 2020-07-28
  • 2018-11-20
  • 2015-09-30
  • 2021-03-10
  • 1970-01-01
  • 1970-01-01
  • 2018-09-05
  • 1970-01-01
相关资源
最近更新 更多