react-nativeprismagql

Prisma: Can I combine two models into one db?


I have two separate model in Prisma schema.

And I need to combine these two models and sort by createdAt.

These two models both have createdAt.

So that I want to get two data sorted by createdAt.

Is that possible to combine two models in Prisma?

model Feed {
  id Int @id @default(autoincrement())
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId Int
  photos String[]
  caption String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  likes Like[]
  comments Comment[]
}

model Poem {
  id Int @id @default(autoincrement())
  user User @relation(fields: [userId], references: [id], onDelete: Cascade)
  userId Int
  poemTitle String
  poemCaption String
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt
  poemLikes Poemlike[]
  poemComments Poemcomment[]
}

Or should I only can do in front-end?

the problem is I take data by 2 in front-end each model.

ex)

Feed Data: 2022-06 / 2022-07 / 2022-08
Poem Data: 2022-09 / 2022-10 / 2022-11

Then I need to sort them : poem 11 -> poem 10 -> poem 09 -> feed 08 -> feed 07 -> feed 06

But since I get data by 2, in current screen I only get data

Feed Data: 2022-07 / 2022-08
Poem Data: 2022-10 / 2022-11

Then sorting will be : poem 11 -> poem 10 -> feed 08 -> feed 07

poem 09 disappears.

how can I solve this problem?


Solution

  • If the two models do not share a relationship, you would need to query for them separately, combine the arrays, and then sort by createdAt.

    const [feeds, poems] = await Promise.all([
      prisma.feed.findMany(), // add whatever filters you need to the "findMany" call
      prisma.poem.findMany()
    ]);
    const dataToSort = [...feeds, ...poems];
    const sortedData = dataToSort.sort((itemA, itemB) => {
      return new Date(itemA.createdAt).getTime() - new Date(itemB.createdAt).getTime()
    });
    return sortedData;