[英]retrieving data from two tables into multidimensional array api json response
I am learning Api development where i want to retrieve data from two tables 我正在学习Api开发,我想从两个表中检索数据
First table (items) contains: 第一个表(项目)包含:
id, feed_id, title, author, content
Second table (feeds): 第二张表格(供稿):
feed_id,title,url
I want to get Json response like: 我想得到像Json的回复:
{
- stories :
[
id
feed_id {
title,
url
}
title
author
]
}
My PHP function to retrieve story biased on id is like: 我的PHP函数用于检索偏向id的故事,例如:
$app->get('/stories/:id', 'authenticate', function($story_id) {
$response = array();
$result = Database::get('db')->table('items')
->eq('rowid', $story_id)
->findOne();
//$response["error"] = false;
if ($result != NULL) {
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => $result["feed_id"],
'title' => $result["title"],
'isBreaking' => $result['isBreaking'],
'author' => $result['author'],
'updated' => $result["updated"],
'url' => $result['url'],
'content' => $result["content"]);
echoRespnse(200, $response);
}
else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
The result i get is like: 我得到的结果是这样的:
{
- "stories": [
{
id
feed_id
title
url
}
]
}
How can i retrieve data from the second tablet (feeds) biased on feed_id and get the data into sub array? 如何从有feed_id偏倚的第二个平板电脑(提要)中检索数据并将数据放入子数组?
as @MikeBrant mentioned you have to use join
between two tables to retrieve correct data. 作为@MikeBrant提到你必须使用join
两个表之间检索正确的数据。 the plain query will be something like this: 普通查询将是这样的:
select items.id, items.title, items.author, items.content, feeds., feeds.title as feed_title, feeds.url from items left join feeds on items.feed_id = feeds.feed_id
and then change your $response['stories']
like this: 然后像这样更改您的$response['stories']
:
$response['stories'] = array(
'id' => $result["id"],
'feed_id' => array(
'title' => $result["feed_title"],
'url' => $result["url"]
),
'title' => $result["title"],
.
.
.
);
you get the idea :) 你明白了:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.