只要选择多对多关系记录,Prisma 就会创建不必要的对象层次结构

Prisma creates unnecessary object hierarchy whenever many-to-many relation records are being selected

我的用户和他们的奖励之间存在多对多关系。使用 Prisma,我创建了一个明确的关系。现在我想 select 给定用户的所有奖励。我写了这个函数:

  async getUserRewards(userId: number) {
    const rewards = await this.prisma.userGainedRewards.findMany({
      where: {
        userId: userId,
      },
      select: {
        reward: true,
      },
    });

    return rewards;
  }

但结果是这样的:

[
    {
        "reward": {
            "id": 2,
            "createdAt": "2022-03-15T14:32:10.709Z",
            "updatedAt": "2022-03-15T14:32:10.709Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    },
    {
        "reward": {
            "id": 3,
            "createdAt": "2022-03-15T14:32:11.479Z",
            "updatedAt": "2022-03-15T14:32:11.479Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    }
]

如您所见,我在“奖励”之前有一个不必要的未命名对象。我怎么能忽略它呢?

这是 Prisma 的预期行为,如果您在 select 子句中添加了其他字段,那么这些字段也将添加到内部对象中。

要展平数据并移除中间未命名对象,您可以通过展开内部奖励对象来实现。

const arr = [
    {
        "reward": {
            "id": 2,
            "createdAt": "2022-03-15T14:32:10.709Z",
            "updatedAt": "2022-03-15T14:32:10.709Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    },
    {
        "reward": {
            "id": 3,
            "createdAt": "2022-03-15T14:32:11.479Z",
            "updatedAt": "2022-03-15T14:32:11.479Z",
            "title": "reward 122",
            "description": "des",
            "price": 2330
        }
    }
]

const updatedArr = arr.map((obj)=>{
    return { ...obj.reward }
})

console.log(updatedArr)

这是输出:

[
    {
        "id": 2,
        "createdAt": "2022-03-15T14:32:10.709Z",
        "updatedAt": "2022-03-15T14:32:10.709Z",
        "title": "reward 122",
        "description": "des",
        "price": 2330
    },
    {
        "id": 3,
        "createdAt": "2022-03-15T14:32:11.479Z",
        "updatedAt": "2022-03-15T14:32:11.479Z",
        "title": "reward 122",
        "description": "des",
        "price": 2330
    }
]