Lets say you have tables like this:
table: Users
- id
- firstName
table: Chat
- id
- type
table: Messages
- id
- type
- fromUserId
- ChatId
- message
table: Chat_User
- ChatId
- UsersId
How can I query my database to get the chats that belong to a user and all the chats and messages in that chat. So basically this data in this structure:
{
"data": [
{
"id": 1,
"type": "dual",
"users": [
{
"id": 1,
"firstName": "bob",
"chatIds": [
1
]
}
],
"messages": [
{
"id": 2,
"type": "text",
"message": "good thanks",
"fromUserId": 1
},
{
"id": 1,
"type": "text",
"message": "hey how are you?",
"fromUserId": 2
}
]
}
]
}
I have tried doing this query:
SELECT JSON_AGG(ROW_TO_JSON(chatty)) AS users
FROM (SELECT *
FROM chat_user
JOIN users
ON users.id = chat_user."usersId"
JOIN message
ON users.id = message."fromUserId"
WHERE chat_user."chatId" IN
(SELECT chat_user."chatId"
FROM chat_user
WHERE "usersId" = 2)
) chatty
which gives :
[
{
"usersId": 1,
"chatId": 1,
"id": 1,
"firstName": "bob",
"lastName": "booby",
"email": "[email protected]",
"id": 1,
"type": "text",
"message": "hey how are you?",
"fromUserId": 1,
"chatId": 1
},
{
"usersId": 2,
"chatId": 2,
"id": 2,
"firstName": "bob",
"lastName": "booby",
"email": "[email protected]",
"id": 2,
"type": "text",
"message": "good thanks",
"fromUserId": 2,
"chatId": 1
},
{
"usersId": 2,
"chatId": 1,
"id": 2,
"firstName": "bob",
"lastName": "booby",
"email": "[email protected]",
"id": 2,
"type": "text",
"message": "good thanks",
"fromUserId": 2,
"chatId": 1
}
]
Which is very far off my desired data structure.