0

I have a question related to writing a "social media" style feed query, but in this case I'm using Prisma 2. I have a music application where I'd like to display a feed of all Albums from Artists that a User follows.

In my schema.prisma, I have the following models:

User

model User {
  id         Int      @id @default(autoincrement())
  email      String   @unique
  following  Artist[]
}

Artist

model Artist {
  id        Int     @id @default(autoincrement())
  name      String
  followers User[]
  albums    Album[]
}

Prisma creates an implicit join table called UserToArtist to track when a User follows an Artist

Album

model Album {
  id          Int      @id @default(autoincrement())
  title       String
  date        DateTime <-- this is an ISO date string
  artists     Artist[] <-- an album can have several artists
}

Prisma creates an implicit join table called ArtistToAlbum to track which Artists are associated to certain Albums.


So how can I create a Prisma query to find all albums of artists that a user follows ordered by Album date? Here was my first attempt, but this doesn't seem to be correct and the albums aren't sorted by date:

const results = await ctx.db.album.findMany({
  where: {
    date: {
      gt: moment().startOf('day').toISOString()
    },
    artists: {
      some: {
        followers: {
          some: {
            id: args.userId, <-- the userId for the feed
          },
        },
      },
    },
  },
  orderBy: {
    date: 'asc',
  },
})

Notice how I have to filter down through two some statements? Just doesn't feel right... What recommendations do you have for a query like this? Thanks!

Jordan Lewallen
  • 1,681
  • 19
  • 54

1 Answers1

0

You can use the fluent API to grab all the artists that a user follows, and it should look something like this:

const followedArtists = await ctx.db.user.findOne({ where: { id: args.userId, } }).following()

From here you can grab the albums from all of those artists and then sort them in your server code to then be sent back as the query result

Rodentman87
  • 640
  • 7
  • 14