简体   繁体   中英

Join multiple left values with one right value

In Codeigniter I am tryign to join two tables with one to many relation. I want to get one result from my table housetype and all of its values/members from other table 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();

So far I get such 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)

First two object values (PkID, Name) are from the first table and the last one (image) is from the second left table. Everything is good but I get array with two elements, when I only need one housetype object.

Is there a way to write above code so that my returned object would look like this:

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)

I need one result from first table and to it I want to join all of its members from the second table.

Can it be done with Codeigniters active record?

As far as your second table has multi records with that primary key, it is better if you don't use joins at all. You can simply get that with two selects.

$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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM