【问题标题】:Codeigniter join returning same record three timesCodeigniter join 三次返回相同的记录
【发布时间】:2015-05-16 09:12:23
【问题描述】:

我在 property_address 表中的列表表 1 中有一条记录,在 property_images 表中有三张图像,它们属于列表表中的那条记录。现在我实际上想要返回单行包含所有图像。但是我得到的是 3 行,因为属性图像表中的每个图像都有 3 个图像,所以它会创建一个新行。

我有三张桌子

  1. 上市
  2. property_address
  3. property_images

这是架构

这里是模型函数。

public function get_listing($where)
    {
        $this->db->select('dl.*,pi.*,ps.*');
        $this->db->from('listing as dl');
        $this->db->join('property_address as ps','ps.property_add_id=dl.prop_id');
        $this->db->join('property_images as pi','pi.listing_id=dl.prop_id','right');
        if(!empty($where))
        {
            $this->db->where($where);
        }
        $query=$this->db->get();
        return $query->result();
    }

这是控制器

public function testin()
    {
        $data=$this->dba->get_listing(array('dl.prop_id'=>2));
        echo "<pre>";
        print_r($data);
        echo "</pre>";
    }

【问题讨论】:

  • 您可以在控制器中查询后执行echo $this-&gt;db-&gt;last_query();,以查看MySQL查询,并使用该查询在phpmyadmin中执行以查看查询是否有问题!
  • 查询运行完美问题是多条记录相同但图像不同
  • 结果是预期的。你在property_images 有 3 行,所以结果将是 3。你应该提供你想要的一行的例子。

标签: php mysql codeigniter join


【解决方案1】:

实际上它可能会返回 3 条记录,因为 property_address 表与列表表有关系,当您加入和检索记录时,它将根据外键和查询返回 3 条记录。

您应该做的是以编程方式管理记录,例如,如果您有 3 个具有不同图像的相同记录,则分别获取相同的记录,而不是循环遍历图像。

例子:

public function testin()
    {
        $data=$this->dba->get_listing(array('dl.prop_id'=>2));
        echo "<pre>";
        print_r($data);
        echo "</pre>";
        echo $data[0]->id;
        echo $data[0]->title;
        echo $data[0]->prop_type;
        echo $data[0]->property_name;
        echo $data[0]->addres;
        etc....
        Now loop over images and you will get all three images
        foreach($data as $row):
        {
          echo $data->image;
        }

}

我希望它会有所帮助。

【讨论】:

  • 所以这意味着我必须以编程方式利用数据,如果有多个相同的记录,只有一个不同的列,就像我现在的情况一样
  • @Vicky 它仅适用于单个列表项。对于多个列表项,您需要以不同的方式进行操作。希望您能做到。
【解决方案2】:

左加入就是你要找的,

public function get_listing($where)
{
    $this->db->select('dl.*,pi.*,ps.*');
    $this->db->from('listing as dl');
    $this->db->join('property_address as ps','ps.property_add_id=dl.prop_id','left');
    $this->db->join('property_images as pi','pi.listing_id=dl.prop_id','right','left');
    if(!empty($where))
    {
        $this->db->where($where);
    }
    $query=$this->db->get();
    return $query->result();
}

【讨论】:

  • 仍然得到 3 个相同的行
猜你喜欢
  • 1970-01-01
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-15
相关资源
最近更新 更多