postgresql Prisma查询仅在类别出现在项目2表关系中时才包括类别

axzmvihb  于 11个月前  发布在  PostgreSQL
关注(0)|答案(1)|浏览(120)

我有一个分类表,

model publish_categories {
  c_id   Int    @id @default(autoincrement())
  name   String
  slug   String
  active Int?
}

字符串
然后我有项目,在项目表中我有一个类别条目,它将多个类别作为数组列出

model publish_items{
id               Int    @id @default(autoincrement())
groups           Int[]
}


虽然每个项目下可能有多个类别,但也可能有没有项目的类别。我正在努力找到一个过滤器,通过Prisma只显示其中有项目的类别列表。我还没有看到任何方法在表之间建立“IN”关系。

const categories = await prisma.publish_categories.findMany({
    select: {
      id: true,
      name: true,
      slug: true
    },
    where: {

    },
    orderBy: {
      name: "asc"
    },
  });

rjee0c15

rjee0c151#

如果要仅在类别与项目关联时才检索类别,则可以使用Prisma查询,该查询使用some筛选器沿着嵌套关系。为了确定是否至少有一个项目满足给定条件,请将items关系与 *'some'**筛选器一起使用。此查询将仅返回至少有一个关联项目的类别。
这就是你如何改变你的查询。

const categoriesWithItems = await prisma.publish_categories.findMany({
  select: {
    id: true,
    name: true,
    slug: true,
  },
  where: {
    // Use a nested relation with count to filter categories with items
    items: {
      some: {
        // Add any additional conditions for items if needed
      },
    },
  },
  orderBy: {
    name: "asc",
  },
});

字符串
希望对你有帮助:)

相关问题