【发布时间】:2014-03-05 13:03:50
【问题描述】:
我想要完成的是查询类别表中所有类别的数据,同时添加一个“posts”属性,该属性列出该类别中所有帖子的 ID 到一个数组中。
数据库表:
'categories' table
+---------+----------+
| id | title |
+---------+----------+
| 100 | "categ1" |
| 101 | "categ2" |
| 102 | "categ3" |
| 103 | "categ4" |
+---------+----------+
'posts' table
+---------+----------+----------+
| id | title | category |
+---------+----------+----------+
| 1 | "abc" | 100 |
| 2 | "def" | 101 |
| 3 | "ghi" | 100 |
| 4 | "jkl" | 102 |
+---------+----------+----------+
输出目标:(json_encode,手动添加'categories'到顶层)
{
"categories": [
{
"id": 100,
"title": "categ1",
"posts": [1, 3] (Post IDs of those in category 10)
}
{
"id": 102,
"title": "categ2",
"posts": [2]
}
{
"id": 103,
"title": "categ3",
"posts": [4]
}
{
"id": 104,
"title": "categ4",
"posts": []
}
]
}
虽然获取类别的基本查询很简单,但我想不出一种方法来根据帖子表和帖子类别/类别 ID 关系生成帖子属性。
如果有不清楚的地方可以提供更多信息。
【问题讨论】: