链接链接关联

时间:2019-04-11 13:32:46

标签: javascript sequelize.js

基本上我有3个实体,即问卷/问题/答案。 1个问题有很多答案,问卷有很多问题。

我正尝试用一种方法来创建调查表及其实现的问题/答案。问题创建好了,答案却没有

调查问卷简化

static addInclude = () => [
        {
            model: seq.models.MCQuestion,
            as: 'questions',
        }
    ];

    static associate = models => {
        this.hasMany(models.Question, {
            foreignKey: 'questionnaireId',
            hooks: true,
            constraints: true,
            onDelete: 'cascade',
            as: 'questions',
        });
    }
    static getInclude = () => [
            {
                model: seq.models.Question,
                as: 'questions',
                required: false,
                include: seq.models.Question.getInclude()
            }
        ];

简化的问题

static addInclude = () => [
        {
            model: seq.models.Answer,
            as: 'answers'
        }
    ];

    static associate = models => {
        this.hasMany(models.Answer, {
            foreignKey: 'questionId',
            hooks: true,
            constraints: true,
            onDelete: 'cascade',
            as: 'answers',
        });
        this.belongsTo(models.Questionnaire, {
            foreignKey: 'questionnaireId',
            as: 'questionniare',
        });
    }

answer

static associate = models => {
            this.belongsTo(models.Question, {
                foreignKey: 'questionId',
                as: 'question',
            });
        };

创建方法

export const add = async (securityObj, data) => {
    try {
        const result = await sequelize.transaction(
            {
                isolationLevel:
                    sequelize.Transaction.ISOLATION_LEVELS.READ_COMMITTED
            },
            transaction =>
                Questionnaire.create(
                    { ...data, tenantId: securityObj.tenantId },
                    {
                        include: Questionnaire.addInclude(),
                        transaction
                    }
                )
        );
        return result;
    } catch (err) {
        throw err;
    }
};

要插入的数据

 {
    label: "Qst!",
    searchText: "Qst1",

   questions: [
      {
        id: "2s1a2076-5c00-11e9-8647-d663bd873d93",
        type: MC,
        label: "Qst",
        searchText: "Qst",
        questionnaireId: "dd98bf22-5bff-11e9-8647-d663bd873d93",
        question: "Qst ?"
        answers: [
          {
            id: "2b9f44ae-5c00-11e9-8647-d663bd873d93",
            answer: "Yes",
            ordering: 1,
            isOpen: false,
            enabled: true
          },
          {
            id: "2b9f44ae-5c00-11e9-8647-d663bd873d93",
            answer: "No",
            ordering: 1,
            isOpen: false,
            enabled: true
          }
        ]
      }
    ]
  }

有什么想法吗?

0 个答案:

没有答案