[英]MYSQL PHP API - Displaying & Fetching multiple rows within rows from another table
我正在為我的移動應用程序創建一個API。 我正在使用PHP MYSQL和Slim框架(與該問題無關)進行開發。
我試圖從我的mysql數據庫中提取多個“ venues”,並為每個“ venue”檢索多個“ venue_images”。 數據庫:
venues venue_images
------ ------------
id PK image_venue_id FK (to venues)
venue_name image_path
active
然后,我需要以這種格式輸出數據:
{
"completed_in":0.01068,
"returned":10,
"results":[
{
"venue_id":"1",
"venue_name":"NameHere",
"images": [
{
"image_path":"http://www.pathhere.com"
},
{
"image_path":"http://www.pathhere2.com"
}
]
}
]
}
因此,基本上,每個場所對圖像進行多次迭代。
我當前的代碼是:
$sql = "
SELECT
venues.id, venues.venue_name, venues.active,
venue_images.image_venue_id, venue_images.image_path
FROM
venues
LEFT JOIN
venue_images ON venue_images.image_venue_id = venues.id
WHERE
venues.active = 1
LIMIT 0, 10
";
$data = ORM::for_table('venues')->raw_query($sql, array())->find_many();
if($data) {
foreach ($data as $post) {
$results[] = array (
'venue_id' => $post->id,
'venue_name' => $post->venue_name,
'images' => $post->image_path
);
}
//Build full json
$time = round((microTimer() - START_TIME), 5);
$result = array(
'completed_in' => $time,
'returned' => count($results),
'results' => $results
);
//Print JSON
echo indent(stripslashes(json_encode($result)));
} else {
echo "Nothing found";
}
我當前的代碼有效,但是會產生以下結果:
{
"completed_in":0.01068,
"returned":10,
"results":[
{
"venue_id":"1",
"venue_name":"The Bunker",
"images":"https://s3.amazonaws.com/barholla/venues/1352383950-qPXNShGR6ikoafj_n.jpg"
},
{
"venue_id":"1",
"venue_name":"The Bunker",
"images":"https://s3.amazonaws.com/barholla/venues/1352384236-RUfkGAWsCfAVdPm_n.jpg"
}
]
}
“地堡”有兩個圖片。 而不是將圖像存儲在場所數組中,而是創建帶有第二張圖像的“ The Bunker”重復行。 就像我之前說過的,我需要在每個場所內迭代多個圖像。 任何幫助將非常感激! 謝謝!
您想使用GROUP_CONCAT
像這樣的東西(可能不是100%准確:))
$sql = "
SELECT
v.id, v.venue_name, v.active,
GROUP_CONCAT(i.image_path) as venue_image_string
FROM
venues v
LEFT JOIN
venue_images i ON i.image_venue_id = v.id
WHERE
v.active = 1
GROUP BY i.image_venue_id
LIMIT 0, 10
";
您可能需要擺弄一些東西,但應該把自己放在正確的軌道上(注意:以CSV格式提供venue_image_string)
為什么不能使用多個查詢代替..? 它更快,更簡單..!
$sql = "SELECT venues.id, venues.venue_name, venues.active FROM venues WHERE venues.active = 1 LIMIT 0, 10";
$data = ORM::for_table('venues')->raw_query($sql, array())->find_many();
if($data) {
foreach ($data as $post) {
$results[] = array ();
$sql = "SELECT image_path FROM venue_images WHERE image_venue_id = $post->id";
$images = ORM::for_table('venue_images')->raw_query($sql, array())->find_many();
$results[] = array (
'venue_id' => $post->id,
'venue_name' => $post->venue_name,
'images' => $images);
}
//Build full json
$time = round((microTimer() - START_TIME), 5);
$result = array(
'completed_in' => $time,
'returned' => count($results),
'results' => $results
);
//Print JSON
echo indent(stripslashes(json_encode($result)));
} else {
echo "Nothing found";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.