'Query to get most popular musician with an aggregated field sum

I have the following database schema:

model Music {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  title     String   @db.VarChar(255)
  duration  Int
  playbacks Int
  artist    Musician?  @relation(fields: [musicianId], references: [id])
  artistId  Int?
}

model Musician {
  id        Int      @id @default(autoincrement())
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  name      String?
  musics    Music[]
  albums    Album[]
}

And I have to return a 3 most popular musicians with an aggregated field totalPlaybacks in each one.

Is this possible to do this using findMany in prisma?

This is my controller:

exports.getTopThree = (req, res) => {
  prisma.artist
    .findMany({
       //should the query be there
    })
    .then((data) => {
      console.log(data);
      res.send({ data });
    })
    .catch((err) => {
      res.status(500).send({
        message: err.message || "Some error occurred while retrieving artists.",
      });
    });
};

Could someone help me on this problem?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source