-
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()..."? |
Beta Was this translation helpful? Give feedback.
Replies: 3 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(). |
Beta Was this translation helpful? Give feedback.
-
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) |
Beta Was this translation helpful? Give feedback.
-
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. |
Beta Was this translation helpful? Give feedback.
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.