|
Hello. I'm trying to use drizzle to make a query that gets all threads along with the most recent message from each thread. Using SQL, the query is: select
*
from
threads t
left join "threadMessages" tm on
tm.thread_id = t.id
where
tm.created_at = (
select
max(created_at)
from
"threadMessages"
where
thread_id = t.id)
or tm.created_at is null;How can I get the same result using "drizzle.select()..."? |
Answered by
Angelelz
Jan 5, 2024
Replies: 4 comments 6 replies
|
I got a similar result using query.threads.findMany(): const result = drizzle.query.threads
.findMany({
with: {
threadMessages: {
orderBy: desc(threadMessages.created_at),
limit: 1,
},
},
})But I still haven't managed to using select(). |
0 replies
|
You can achieve the same result by using querybuilder db.select().from(threads)
.leftJoin(threadMessages, eq(threadMessages.threadId, threads.id))
.orderBy(desc(threadMessages.createdAt))
.limit(1) |
2 replies
|
Here's how you do this with drizzle: const sq = db.select({ max: sql`max(${threadMessages.createdAt})` }).from(threadMessages).where(eq(threads.id, threadMessages.threadId));
const query = await db.select()
.from(threads)
.leftJoin(threadMessages, eq(threadMessages.threadId, threads.id))
.where(or(
eq(threadMessages.createdAt, sq),
isNull(threadMessages.createdAt)
));This might work. Let me know if it doesn't there might be other ways to do it. |
4 replies
Answer selected by
tjapa
|
I had a similar problem that I couldn't find a good solution for (but I did find this thread), so I'm putting it here in case someone else finds it. I needed to get all users that are also in the blocklist table. eg SELECT * FROM users WHERE user_id IN (SELECT user_id FROM blocked)This worked for me: import { inArray } from "drizzle-orm";
const idsOfBlocked = db
.selectDistinct({ user_id: blocked.user_id })
.from(blocked);
const query = db
.select()
.from(users)
.where(
inArray(users.user_id, idsOfBlocked)
) |
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's how you do this with drizzle:
This might work. Let me know if it doesn't there might be other ways to do it.