繁体   English   中英

使用外键从表中检索数据

[英]Retrieve data from table with foreign key

我想知道如何使用2个外键从table3检索数据。 我将首先向您展示我的桌子,然后尝试解释我要做什么以及如何做。

Table1
ID Primary key

Table2
ID Foreign key
foodID Foreign Key

Table3
foodID Primary key
food 

因此,我首先要在第一个表中获取ID,然后将其与第二个表中的ID进行比较,然后获得foodID(请注意,这种关系是1对多,因此每个ID我可以有很多foodID)。 然后,我想使用foodID输出所有食物。 这是我的意思的一个例子,因为我不太清楚。

假设我们有ID = 1 ,在这里我们有foodID = 1foodID = 2 ,最后,foodID为1表示food = pasta ,foodID为2表示food = mince meat 因此,最后我想同时输出pastamince meat

这是我到目前为止的代码,在上面的示例中,它将仅输出pasta而不mince meat

public function getFood($id){
        $data = $this->db->get_where('Table2', array('ID' => $id)); //Where $id is the ID in Table1
        $Result = $data->result();
        foreach($Result as $row){
            $fID = $row->foodID;
        }
        $data = $this->db->get_where('Table3', array('foodID' => $fID));
        return($data);
    }  

这是我输出食物的观点:

foreach($results as $row){
            echo $row->food;
        }

您只需要进行加入:

public function getFood($id){
    $this->db->select('*');
    $this->db->from('Table3');
    $this->db->join('Table2', 'Table2.ID = Table3.foodID');
    $this->db->where('Table2.Id',$id);

    $result = $this->db->get();
    return $result;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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