Search code examples
prismaprisma-graphqlnexus-prisma

Prisma2: use user id in related table in create function


I am trying to create a user that is the child of another user. I am managing this relationship by having a User table where all users, parents and children, are stored. There is a seperate table that just has the id of the child and the id of the parent.

My problem is that when I create a child account I want to create an entry in the Relationship table using the user id that would be created. I am not sure at all how I should go about this.

// schema.sql

CREATE TABLE "public"."Relationship" (
    id SERIAL PRIMARY KEY NOT NULL,
    parent_id INT NOT NULL,
    FOREIGN KEY (parent_id) REFERENCES "User" (id),
    child_id INT NOT NULL,
    FOREIGN KEY (child_id) REFERENCES "User" (id)
)

CREATE TABLE "public"."User" (
    id SERIAL PRIMARY KEY NOT NULL,
    name VARCHAR(128) NOT NULL,
    email VARCHAR(128) UNIQUE,
    password VARCHAR(128) NOT NULL,
    isChild BOOLEAN NOT NULL DEFAULT false
    created_at TIMESTAMP NOT NULL DEFAULT NOW();
);

// CreateChild User mutation

export const createChildAccount = mutationField('createChildAccount', {
  type: 'User',
  args: {
    name: stringArg({ required: true }),
    password: stringArg({ required: true }),
  },
  resolve: async (_parent, { name, password }, ctx) => {
    const userId = getUserId(ctx);
    if (!userId) {
      // TODO -think I might need to throw an error here
      return;
    }
    const user = await ctx.prisma.user.create({
      data: {
        name,
        password,
        ischild: true,
        child: {
          create: { child_id: ???????? },
        },
        parent: {
          connect: {id: userId}
        }
      },
    });
    return user;
  },
});

Should I actually be creating a Relationship and then using that to connect the parent and create the child?


Solution

  • In hindsight it was an easy solution. I created the entry in the User and then created an entry in the Relationship table where I connected the parent and child accounts

    export const createChildAccount = mutationField('createChildAccount', {
      type: 'User',
      args: {
        name: stringArg({ required: true }),
        password: stringArg({ required: true }),
      },
      resolve: async (_parent, { name, password }, ctx) => {
        const userId = getUserId(ctx);
        if (!userId) {
          return;
        }
        const user = await ctx.prisma.user.create({
          data: {
            name,
            password,
            ischild: true,
          },
        });
        await ctx.prisma.relationship.create({
          data: {
            parent: {
              connect: {
                id: userId,
              },
            },
            child: {
              connect: {
                id: user.id,
              },
            },
          },
        });
        return user;
      },
    });