count() for join tables in query API

Usage


I have a user page where you can see how many of their answers were considered correct (a person who asked a question accepted them, like on github).

3 tables are used:
  • users
  • questions
  • answers
each answer has a column authorId which refers user.id, each question has acceptedAnswerId which refers answer.id

export function queryUser({ userId }: { userId: number }) {
  return db.query.usersTable.findFirst({
    where: (t, { eq }) => eq(t.id, userId),
    with: {
      questions: {
        with: {
          answers: {
            columns: {
              id: true,
              authorId: true,
            },
          },
          usersLikes: {
            columns: {
              questionId: true,
              userId: true,
            },
          },
          usersViews: {
            columns: {
              questionId: true,
            },
          },
        },
      },
    },
    extras: (t) => ({
      // a number of "answers" (table, see above) whose "authorId" === t.id 
      // should return an integer 0/1/2/3/4/5/...
      acceptedAnswers: count(t.id).as('accepted_answers'),
    }),
  })
}


Draw your attention to the extras, what should be written there? I am not quite following
Was this page helpful?