0

我有 3 张item桌子,一张是桌子,一张是note桌子,另一张是note image桌子。

当用户查看项目详细信息时,该项目的所有注释都会被拾取(注释表中有一个 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;
    }
}
4

1 回答 1

1

很难知道你什么时候没有在表格中发布你的关系,而是做了一些假设

 $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;


   }
于 2013-06-03T18:23:17.657 回答