mahmoudalsof
mahmoudalsof

Reputation: 123

Many-to-Many relationship Prisma update

I have 2 tables. Member & Event and the idea is that each member can attend 0 or many events. And each event can have 0 or many members. The event already exists, the code should just add the event to the member based on their ID.

Schema Model:

model Member {
  id             String   @id @default(uuid())
  firstName      String
  lastName       String
  emailAddress   String
  mobileNumber   String
  whatsAppNumber String   @default("null")
  password       String
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt
  events         Event[]
}

model Event {
  id           String   @id @default(uuid())
  name         String
  date         DateTime
  meetingPoint String
  meetingTime  String
  details      String
  members      Member[]

}

The issue is, I am not able to figure out how to add an event to an existing member. Resources online are not working either.

Query Code:

exports.registerForEvent = async (req, res, next) => {
  try {
    const { memberId, eventId } = req.body;

    const _event = await prisma.event.findUnique({ where: { id: eventId } });

    if (_event) {
      const _member = await prisma.member.upsert({
        where: { id: memberId },
        update: {
          events: _event,
        },
      });

      if (_member) {
        res.status(200).send("OK");
      } else {
        generateError("Failed", req, next);
      }
    }
  } catch (err) {
    generatDefaultError(err, req, next);
  }
};

Console error:

PrismaClientValidationError:
Invalid `prisma.member.upsert()` invocation:

{
  where: {
    id: '40d00e11-cfe7-4707-8f19-0c13cd7e7fc7'
  },
  update: {
    events: {
    ~~~~~~
      id: '52294035-3a4e-431a-ae1c-b2f12525dc3e',
      name: 'Event Name',
      date: new Date('2021-01-14T20:00:00.000Z'),
      meetingPoint: 'Meeting Point',
      meetingTime: 'Meeting Time',
      details: 'Event details'
    }
  },
+ create: MemberCreateInput | MemberUncheckedCreateInput
}

Unknown arg `events` in update.events for type MemberUncheckedUpdateInput. Did you mean `posts`?
Argument create is missing.

Note: Lines with + are required

I'm brand new to Prisma and trying to work my head on how it works. Any help would be appreciated.

Upvotes: 1

Views: 3851

Answers (1)

mahmoudalsof
mahmoudalsof

Reputation: 123

So I manged to figure it out with a lot of trial and error. I wanted to post the answer here incase anyone else was looking for a similar solution:

The keyword here is to use connect

Working code:

exports.registerForEvent = async (req, res, next) => {
  try {
    const { memberId, eventId } = req.body;

    // Find the event by it's ID
    const _event = await prisma.event.findUnique({ where: { id: eventId } });

    // Find the member by their ID
    const _member = await prisma.member.update({
      where: { id: memberId },
      data: {
        events: {
          connect: [{ id: _event.id }], // connect that member with the event ID
        },
      },
    });

    if(_member) {
        res.status(200).send("ok")
    }
  } catch (err) {
    generatDefaultError(err, req, next);
  }
};

Upvotes: 7

Related Questions