[英]How can I retrieve data from a table and using a foreign key retrieve data from another table?
[英]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 = 1
和foodID = 2
,最后,foodID為1表示food = pasta
,foodID為2表示food = mince meat
。 因此,最后我想同時輸出pasta
和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);
}
這是我輸出食物的觀點:
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.