2013-06-03 67 views
0

我有3個表格1是item表格,一個是note表格,另一個是note image表格。Codeigniter/PHP,2 Mysql Tables,Multiple Queries

當用戶查看項目的詳細信息,所有音符都拿起該項目(有在注意表中的ITEM_ID場)

該票據可以附加到他們這些多個圖像存儲在平面文件,但是被「音符圖像」表引用。

現在,當顯示項目詳細信息時,我運行查詢以獲取項目的所有註釋...足夠簡單,然後將這些結果循環輸出到頁面上。現在

問題將圖像添加到筆記後出現的時候,你會如何去查詢所有音符的項目說

SELECT * FROM notes WHERE item = 1

那麼你會如何循環,雖然結果數組讓所有音符圖形的便條說

SELECT * FROM note_img WHERE note_img_noteid = 27 

它傷害了我的頭,因爲一點點,我不能想象如何獲得結果並將其輸出PHP

---編輯---

想我可能拿到了它,

SELECT 
d.door_note_id, 
d.door_note_doorid, 
d.door_note_timestamp, 
d.door_note_editedtime, 
d.door_note_text, 
u.user_name AS created_by, 
e.user_name AS edited_by, 
i.door_img_id AS img_id, 
i.door_img_url AS img_url 

FROM 
user u, 
door_note d 

LEFT JOIN 
user e 
ON 
user_id = d.door_note_editeduserid 
LEFT JOIN 
door_img i 
ON 
door_img_noteid = d.door_note_id 
WHERE 
d.door_note_doorid = 214 
AND 
u.user_id = d.door_note_userid 

然後我用這個:

foreach ($result->result() as $row){ 
    if(!isset($my_items[$row->door_note_id])){ //the note id becaoms a key 
     //here you set up an array for all the note details 
     $my_items[$row->door_note_id] = array('door_note_id'=>$row->door_note_id, 
     'door_note_doorid'=>$row->door_note_doorid, 
     'door_note_timestamp'=>$row->door_note_timestamp, 
     'door_note_editedtime'=>$row->door_note_editedtime, 
     'door_note_text'=>$row->door_note_text, 
     'created_by'=>$row->created_by, 
     'edited_by'=>$row->edited_by, 
     'images'=>array()); 
    } 
    //if the note has any images add them to the images array for that note. 
    if(isset($row->img_url)){ 
     $my_items[$row->door_note_id]['images'][] = $row->img_url; 
    } 
} 
+0

我想我可能需要做2個查詢,因爲在筆記上的圖像是可選的,但我不知道:S。 – Sam

回答

1

它很難知道你什麼時候避風港」 t發表你的關係,但採取一些假設

$query = "SELECT items.id as item_id, items.name as item_name, notes.id as note_id, 
    notes.description as note_description, note_image.image as note_image from notes 
    LEFT JOIN notes ON items.id = notes.item_id 
    LEFT JOIN note_image ON notes.id = note_image.note_img_noteid"; 

//this wil fetch all you items with description, notes and images, because item can have multiple notes, your result wil have multiple entires of the item. so you have to index correctly to use in views 

$result = $this->db->query($query) 

$my_items = array(); 

foreach ($result->result() as $row){ 

    if(!isset($my_items[$row->item_id])){ //you item it becaoms a key 
     //here you set up an array for all your items 
     $my_items[$row->item_id] = array('item_name'=>$row->item_name, 'notes'=>array()); 
     } 
    //here you stroe all images fro a note 
    if(!isset($my_items[$row->item_id]['notes'][$row->note_id])){ 

      $my_items[$row->item_id]['notes'][$row->note_id] = array('note_description'=>$row->note_description, 'images'=>array()); 

     } 

     $my_items[$row->item_id]['notes'][$row->note_id]['images'][] = $row->note_image; 


    } 
+0

這看起來應該可以工作,我需要稍微改變一下名字等等,但是當我測試它時,我會回發,只是整理出我用圖像上傳腳本找到的另一個問題><謝謝! – Sam