使用Prisma编写可变数量的数据库条目

huangapple go评论94阅读模式
英文:

Writing a variable number of database entries with Prisma

问题

我正在开发一个应用程序,该应用程序为每个人分配每周的工作天数,并将他们的日程安排写入关系数据库中使用Prisma。实际上,伪代码如下所示:

const createTutor = await prisma.tutor.create({
    data: { 
        tutorName: tutorName,
        tutorPhone: +tutorPhone,
        tutorRate: +tutorRate,
        tutorEmail: tutorEmail,
        availability: { **这是我不知道该怎么做的地方理想情况下我需要将可用的天数条目包括开始时间和结束时间以可变数量写入数据库并将导师与其可用性条目以及可用性条目与导师连接起来** }
    }
});

以下是这两个数据库条目的模式:

model Tutor {
    tutorName         String               @unique
    tutorAvailability DailyAvailibility[]
    tutorRate         Int
    assignedStudents  TutoringAssignment[]
    linkedUser        User?
    completedSessions CompletedSession[]
    tutorPhone        BigInt
    tutorEmail        String
}

model DailyAvailibility {
    id                    Int    @id @unique @default(autoincrement())
    tutor                 Tutor  @relation(fields: [tutorName], references: [tutorName])
    tutorName             String
    dayOfWeek             Int //0表示星期日,6表示星期六
    beginningAvailability Int
    endingAvailability     Int
}

我想正确地完成这个任务,目前我已经能够正确地写入所有条目,但只能将tutorName与其dailyAvailibilty条目关联起来,而不能反向关联。以下是我目前用于执行此操作的API代码(如果有助于理解我想要做什么):

async function createAvailability(availability:any, tutorName:any) {
    for(let x=0; x<6; x++) {
        if(availability[x] != null) {
            let newAvailability = await prisma.dailyAvailibility.create({
                data: {
                    dayOfWeek:x,
                    beginningAvailability: +availability[x].beginningAvailability,
                    endingAvailability: +availability[x].endingAvailability,
                    tutor: {
                        connect: {
                            tutorName: tutorName
                        }
                    }
                }
            });
        }
    }
}

我希望以一种正确的方式一次性完成所有操作,使导师条目正确连接到其每日可用性,并且每日可用性正确连接到其导师。我还应该提到,这是一个PostgreSQL数据库。

谢谢您的帮助!

英文:

I am working on an app that takes an individual and assigns them a set number of days per week for them to work, then it writes their schedule to a relational database using Prisma. In practice this looks like the following psudocode:

 const createTutor = await prisma.tutor.create({
        data: { 
            tutorName: tutorName,
            tutorPhone: +tutorPhone,
            tutorRate: +tutorRate,
            tutorEmail: tutorEmail
            availability: { **This is where I don&#39;t know what to do. Ideally I need to write a variable number of available day entries (that include a beginning time and an end time) to the database and connect both the tutor to their availability entries and the availability entries to the tutor.** }

Here is what my schema looks like for these two database entries:

model Tutor {
  tutorName         String               @unique
  tutorAvailability DailyAvailibility[]
  tutorRate         Int
  assignedStudents  TutoringAssignment[]
  linkedUser        User?
  completedSessions CompletedSession[]
  tutorPhone        BigInt
  tutorEmail        String
}

model DailyAvailibility {
  id                    Int    @id @unique @default(autoincrement())
  tutor                 Tutor  @relation(fields: [tutorName], references: [tutorName])
  tutorName             String
  dayOfWeek             Int //0 being Sunday and 6 Saturday
  beginningAvailability Int
  endingAvailability     Int
}

I'd love to know how to do this correctly, I technically have it writing all the correct entries but it only links the tutorName to their dailyAvailibilty entries, it does not link the opposite. Here's the code I have now for my API that does this (if it helps understand what I am trying to do)

async function createAvailability(availability:any, tutorName:any) {
    
    for(let x=0; x&lt;6; x++) {
        if(availability[x] != null) {
          let newAvailability = await prisma.dailyAvailibility.create({
            data: {
                dayOfWeek:x,
                beginningAvailability: +availability[x].beginningAvailability,
                endingAvailability: +availability[x].endingAvailability,
                tutor: {
                    connect: {
                        tutorName: tutorName
                    }
                }
            }
          })
        }
    }
}

What I want to do is write this all at once in such a way that the tutor entry is connected correctly to their dailyAvailabilities and the dailyAvailabilities all correctly are linked to their tutors. I should mention this is a postgresql database as well.

Thanks for any help!

答案1

得分: 0

你可以使用create字段或connectOrCreate来创建你的可用性,就像这样:

  const tutor = await prisma.tutor.create({
    data: {
      tutorName: 'tutorName',
      tutorPhone: 1,
      tutorRate: 1,
      tutorEmail: 'tutorEmail',
      tutorAvailability: {
        create: [
          { beginningAvailability: 1, endingAvailability: 1, dayOfWeek: 1 },
          { beginningAvailability: 2, endingAvailability: 2, dayOfWeek: 2 },
        ],
      },
    },
  });

然后,当你查询数据时,只需在查询时使用include来获取关联的另一侧:

  const availabilityWithTutor = await prisma.dailyAvailibility.findFirst({
    include: {
      tutor: true,
    },
  });

  // Tutor
  availabilityWithTutor?.tutor
  
  const tutorWithAvailability = await prisma.tutor.findFirst({
    include: {
      tutorAvailability: true,
    },
  });
 
  // Array<DailyAvailibility>
  tutorWithAvailability?.tutorAvailability
英文:

You can use create field or connectOrCreate to create your availabilities right way, like that:

  const tutor = await prisma.tutor.create({
    data: {
      tutorName: &#39;tutorName&#39;,
      tutorPhone: 1,
      tutorRate: 1,
      tutorEmail: &#39;tutorEmail&#39;,
      tutorAvailability: {
        create: [
          { beginningAvailability: 1, endingAvailability: 1, dayOfWeek: 1 },
          { beginningAvailability: 2, endingAvailability: 2, dayOfWeek: 2 },
        ],
      },
    },
  });

And then to get either side of relation you just need to include it when you query for data:


  const availabilityWithTutor = await prisma.dailyAvailibility.findFirst({
    include: {
      tutor: true,
    },
  });

  // Tutor
  availabilityWithTutor?.tutor
  
  const tutorWithAvailability = await prisma.tutor.findFirst({
    include: {
      tutorAvailability: true,
    },
  });
 
  // Array&lt;DailyAvailibility&gt;
  tutorWithAvailability?.tutorAvailability

huangapple
  • 本文由 发表于 2023年8月9日 01:13:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76861834.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定