typeorm query to add another option to a question in many to many relationship

Viewed 80

I have two tables questions and options. I already have options associated with question.how i delete a particular option from the question. I have a typeorm query but right now it deletes all the options from a question.i only want to delete one option from question. I have a many to many relationship with questions and options.

questionsRouter.post('/questions/unassign-options', async (ctx: any) => {
  const { optionId, questionId } = ctx.request.body;
  const questionRepository = getRepository(Question);
  const optionRepository = getRepository(Option);
  // const option = await optionRepository.findOne({ id: optionId });
  const question = await questionRepository.findOne({ id: questionId });

  question.options = null
  console.log("=====question===", question);
  await questionRepository.save(question);
    ctx.status = 200;
    ctx.body = {
        success: "true",
        data: question
    }
});

Schemas:

import {
    Column,
    Entity,
    JoinColumn,
    JoinTable,
    ManyToMany,
    ManyToOne,
    OneToMany,
    PrimaryGeneratedColumn    
} from 'typeorm';
import { Account } from './account.model';
import { Question } from './questions.model';

@Entity()
export class Option {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({
        nullable: true
    })
    text: string;

    @ManyToMany(type => Question, question => question.options)
    questions: Question[];
}

Questions:

import {
    Column,
    Entity,
    JoinColumn,
    JoinTable,
    ManyToMany,
    ManyToOne,
    OneToMany,
    PrimaryGeneratedColumn    
} from 'typeorm';
import { Account } from './account.model';
import { Option } from './options.model';

@Entity()
export class Question {
    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    questionText: string;

    @ManyToMany(type => Option, option => option.questions, { eager: true })
    @JoinTable()
    options: Option[];
}

0 Answers
Related