zacznę od danych:
Posiadam trzy tabele (w poniższym przykładzie table i ich struktura są fikcyjne, ale dobrze obrazują o co mi chodzi)
news
ID - identyfikator
contents - treść aktualności
photos
photoID - identyfikator
newsID - ID newsa, do którego odnosi się zdjęcie
path - ścieżka do obrazu
comments
commentID - identyfikator
newsID - ID newsa, do którego odnosi się komentarz
author - autor komentarza
contents - treść komentarza
Jeden news może posiadać dowolną ilość zarówno zdjęć jak i komentarzy, czyli mamy podwójną relację jeden-do-wielu.
Teraz chciałbym otrzymać taki wynik zapytania:
Kod
Array
(
[0] => Array
(
[ID] => 1
[contents] => ...
[photos] => Array
(
[0] => ...
[1] => ...
)
[comments] => Array
(
[0] => Array
(
[author] => ...
[contents] => ...
)
[1] => Array
(
[author] => ...
[contents] => ...
)
[2] => Array
(
[author] => ...
[contents] => ...
)
)
)
[1] => Array
(
[ID] => 2
[contents] => ...
[photos] => Array
(
[0] => ...
[1] => ...
)
[comments] => Array
(
[0] => Array
(
[author] => ...
[contents] => ...
)
[1] => Array
(
[author] => ...
[contents] => ...
)
[2] => Array
(
[author] => ...
[contents] => ...
)
)
)
[2] => Array
(
[ID] => 4
[contents] => ...
[photos] => Array
(
[0] => ...
[1] => ...
)
[comments] => Array
(
[0] => Array
(
[author] => ...
[contents] => ...
)
[1] => Array
(
[author] => ...
[contents] => ...
)
[2] => Array
(
[author] => ...
[contents] => ...
)
)
)
)
(
[0] => Array
(
[ID] => 1
[contents] => ...
[photos] => Array
(
[0] => ...
[1] => ...
)
[comments] => Array
(
[0] => Array
(
[author] => ...
[contents] => ...
)
[1] => Array
(
[author] => ...
[contents] => ...
)
[2] => Array
(
[author] => ...
[contents] => ...
)
)
)
[1] => Array
(
[ID] => 2
[contents] => ...
[photos] => Array
(
[0] => ...
[1] => ...
)
[comments] => Array
(
[0] => Array
(
[author] => ...
[contents] => ...
)
[1] => Array
(
[author] => ...
[contents] => ...
)
[2] => Array
(
[author] => ...
[contents] => ...
)
)
)
[2] => Array
(
[ID] => 4
[contents] => ...
[photos] => Array
(
[0] => ...
[1] => ...
)
[comments] => Array
(
[0] => Array
(
[author] => ...
[contents] => ...
)
[1] => Array
(
[author] => ...
[contents] => ...
)
[2] => Array
(
[author] => ...
[contents] => ...
)
)
)
)
Ewentualnie zdjęcia również mogą być jako tablice (z jednym indeksem).
Powyższą tablicę mógłbym otrzymać wykonując trzy zapytania i tworząc w pętli ostateczną formę:
<?php $news = $db->getRows('SELECT * FROM news;'); $photos = $db->getRows('SELECT * FROM photos;'); $comments = $db->getRows('SELECT * FROM comments;'); foreach($news as $n){ 'ID' => $n['ID'], 'contents' => $n['contents'], ); } foreach($photos as $p){ $result[$p['newsID']]['photos'][] = $p['path']; } foreach($comments as $c){ 'author' => $c['author'], 'contents' => $c['contents'] ); } ?>
Ale zastanawiam się (właściwie z czystej ciekawości) czy istnieje możliwość wykonania tego inaczej (czyt.: wydajniej).
Chociaż te dane ($result) i tak będą cacheowane.

Pozdrawiam