简体   繁体   English

使用外键从表中检索数据

[英]Retrieve data from table with foreign key

I was wondering how can I retrieve data from table3 with the use of 2 foreign keys. 我想知道如何使用2个外键从table3检索数据。 I will show you my tables first then try to explain what I am trying to do and how I am doing it. 我将首先向您展示我的桌子,然后尝试解释我要做什么以及如何做。

Table1
ID Primary key

Table2
ID Foreign key
foodID Foreign Key

Table3
foodID Primary key
food 

So I would first get the ID in the first table and compare it with the ID in the second table and get a foodID (note this relationship is a 1 to many, so I can have many foodIDs per ID). 因此,我首先要在第一个表中获取ID,然后将其与第二个表中的ID进行比较,然后获得foodID(请注意,这种关系是1对多,因此每个ID我可以有很多foodID)。 Then I want to output all foods by using the foodID. 然后,我想使用foodID输出所有食物。 Heres an example of what I mean because I don't feel its too clear. 这是我的意思的一个例子,因为我不太清楚。

Say we have and ID = 1 and in this we have foodID = 1 and foodID = 2 and lastly foodID of 1 means food = pasta and foodID of 2 means food = mince meat . 假设我们有ID = 1 ,在这里我们有foodID = 1foodID = 2 ,最后,foodID为1表示food = pasta ,foodID为2表示food = mince meat So in the end I would like to output both pasta and mince meat . 因此,最后我想同时输出pastamince meat

Heres the code I have so far, in the example above it will only output pasta and not mince 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);
    }  

Heres my view where I output the food: 这是我输出食物的观点:

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

You just need to do a join: 您只需要进行加入:

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