© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
Drizzle TeamDT
Drizzle Team•2y ago•
3 replies
Anas Badran

Query based on nested relation

I need help modifying the query code to properly query the chat where it has the the two members.
export const findOrCreateChat = async (fromID: number, toID: number) => {
  const existingchat = await db.query.chats.findFirst({
    with: { members: true },
     where(fields, { and, eq }) {
      // the line below needs fix.
      return and(eq(chatMembers.userID, fromID), eq(chatMembers.userID, toID));
     },

  });
  if (existingchat) {
    return existingchat;
  }

  const newChat = await db
    .insert(chats)
    .values({
      name: `new chat`,
    })
    .returning();

  await db.insert(chatMembers).values([
    { chatID: newChat[0].id, userID: fromID },
    { chatID: newChat[0].id, userID: toID },
  ]);

  return newChat[0];
};
export const findOrCreateChat = async (fromID: number, toID: number) => {
  const existingchat = await db.query.chats.findFirst({
    with: { members: true },
     where(fields, { and, eq }) {
      // the line below needs fix.
      return and(eq(chatMembers.userID, fromID), eq(chatMembers.userID, toID));
     },

  });
  if (existingchat) {
    return existingchat;
  }

  const newChat = await db
    .insert(chats)
    .values({
      name: `new chat`,
    })
    .returning();

  await db.insert(chatMembers).values([
    { chatID: newChat[0].id, userID: fromID },
    { chatID: newChat[0].id, userID: toID },
  ]);

  return newChat[0];
};
Drizzle TeamJoin
The official Discord for all Drizzle related projects, such as Drizzle ORM, Drizzle Kit, Drizzle Studio and more!
11,879Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

how to query based on relation?
Drizzle TeamDTDrizzle Team / help
2y ago
query based on deep relations
Drizzle TeamDTDrizzle Team / help
2y ago
nested relation
Drizzle TeamDTDrizzle Team / help
2y ago
Nested joins / where on relation
Drizzle TeamDTDrizzle Team / help
3y ago