So I've got the following tables setup:
thread:
- id
- created_at
thread_users:
- id
- thread_id -> FK thread
- user_id -> FK users (the user who is in the thread)
- joined_at
users:
- id
- name
- etc...other relevant details for user
Current functionality: When a user clicks on another user (e.g there FRIEND in the app), it will open the message thread between the 2 users (it should grab the msgs between the 2 users). To determine WHICH thread to use (we need to find the thread_id between the 2 users), we must query the thread_users table using the HTTP_REQUEST_USER (user who sent the GET request) & and the user_id PARAM passed in the http GET request.
Once I do this: select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID
It will return a bunch of threads that the users are in, I then group the returned results using the lodash groupBy method: (which basically MOVES all the results into there corresponding thread objects - E.g 6: [ { user1 }, { user2 } ]
- This represents the thread_id 6)
const groupedThreads = _.groupBy(foundThreadUsers, 'thread_id');
From here I loop through each of the found threads (groupedThreads will contain objects THAT contain the arrays of user in each of the threads)
Object.keys(groupedThreads).forEach((key) => {
const thr = groupedThreads[key].filter(tu => tu.user_id === currentUserId || tu.user_id === userId);
console.log(thr, 'FOUND THREAD inside loop after filter');
/**
* @TODO add something here which will take into account pluralbot
*/
if (thr.length === 2) {
foundThread = thr[0];
}
});
However, this bit of logic doesn't work:
if (thr.length === 2) {
foundThread = thr[0];
}
Because the select * from ... (query listed above ^^), only returns the thread_users that match the user ids passed into the where user_id = x OR user_id = y.
I want to be able to select * from thread_users where user_id = HTTP_REQUEST_USER_ID OR user_id = GET_REQUEST_PARAM_USER_ID
BUT also return the other users WHO match the found thread_users.thread_id. Is this possible? Or is there another way I could find the thread between the 2 users?