What I'm trying to accomplish is query the data for all categories in the categories table, but also add a "posts" property that lists out the IDs of all posts within that category into an array.
Database tables:
'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 |
+---------+----------+----------+
Output goal: (json_encode, manually add 'categories' to top-level)
{
"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": []
}
]
}
While the basic query of getting the categories is easy, I can't figure out a way to generate the posts property based off the posts table and the posts category/category id relationship.
Can provide any more information if anything is unclear.