简体   繁体   中英

The sequelize many-to-many setter does not exist

I'm trying to define a many-to-many relationship through Sequalize, but I can't seem to get the hang of applying the relationship after creating the elements.

The many-to-many relationship is between LegalFoundation and Case , and LegalCase has been defined in the DB, so it seems like belongsToMany() does its job.

However, after making sure that all of the LegalFoundations are defined, and the Case is created, I'm struggeling with defining the relationship between the two.

It seems like created_case is missing the required function: UnhandledPromiseRejectionWarning: TypeError: created_case.addLegalFoundation is not a fun n is not a function . However, all the docs I've read show that the correct element should be returned by a create function. So I'm a bit stumped.

The GET-request returns column legal_foundations->LegalCase.case_id does not exist if thats any help in debugging.

Hope someone can show me the way!

database.js

const Sequelize = require('sequelize')

const database = new Sequelize('#####', '#####', '#####', {
    dialect: 'postgres',
    operatorsAliases: Sequelize.Op
})

const District = database.define('district', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    name: { type: Sequelize.STRING, allowNull: false}
});

const LegalFoundation = database.define('legal_foundation', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    text: {type: Sequelize.TEXT, allowNull: false}
});

const Case = database.define('case', {
    id: {
        type: Sequelize.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    ref: {type: Sequelize.TEXT},
    report: {type: Sequelize.ARRAY(Sequelize.TEXT)},
    consideration: {type: Sequelize.ARRAY(Sequelize.TEXT)},
    decision: {type: Sequelize.ARRAY(Sequelize.TEXT)},
    date: {type: Sequelize.DATE}
});

District.hasMany(Case)
LegalFoundation.belongsToMany(Case, {through: 'LegalCase', as: 'cases', foreignKey: "case_id"})
Case.belongsToMany(LegalFoundation, {through: 'LegalCase', as: 'legal_foundations', foreignKey: "legal_foundation_id"})

module.exports = {
    database,
    District,
    LegalFoundation,
    Case
}

case.js

const express = require('express')
const { Case, District, LegalFoundation } = require('./db/database')
const { Op, Sequelize } = require("sequelize");

const router = express.Router()

router.post('/', async (req, res, next) => {
    try {
        const {ref, report, consideration, decision, legal_foundation, date, district} = req.body;
        const [district_ins, created_d] = await District.findOrCreate({
            where: {
                name: district
            },
        });
        foundations = [];
        if (typeof legal_foundation == 'object'){
            legal_foundation.forEach(async element => {
                let [f, created_f] = await LegalFoundation.findOrCreate({
                    where: {
                        text: element
                    }
                });
                foundations.push(f.id)
            });
        } else {
            let [f, created_f] = await LegalFoundation.findOrCreate({
                where: {
                    text: legal_foundation
                }
            });
            foundations.push(f.id)
        }
        const created_case = await Case.create({
            ref: ref,
            report: report,
            consideration: consideration,
            decision: decision,
            date: date,
            districtId: district_ins.id
        });

        foundations.forEach(async element => {
            await created_case.addLegalFoundation(element);
        });

        res.json({success: true, id})
    }
    catch (error) {
        res.json({success: false, error: error})
    }
})

router.get('/', async (req, res, next) => {
    try{
        const all = await Case.findAll({include: {
            model: LegalFoundation,
            as: 'legal_foundations'
        }});
        res.json({success: true, item: all});
    }
    catch (error) {
        res.json({success: false, error: error.message})
    }
})

module.exports = router;

You have several problems here:

  1. Incorrect belongsToMany associations. foreignKey should indicate to a field of a model whose method belongsToMany you call:
LegalFoundation.belongsToMany(Case, {through: 'LegalCase', as: 'cases',
  foreignKey: "legal_foundation_id", otherKey: "case_id" })
Case.belongsToMany(LegalFoundation, {through: 'LegalCase', as: 'legal_foundations', 
  foreignKey: "case_id", otherKey: "legal_foundation_id"})
  1. forEach method cannot wait for async iterations. You should use for of :
for (const element of legal_foundation) {
  let [f, created_f] = await LegalFoundation.findOrCreate({
    where: {
      text: element
    }
  });
  foundations.push(f.id)
}
for (const element of foundations) {
  await created_case.addLegalFoundation(element);
}
  1. I suppose because you used legal_foundations name with _ then try to look at methods of created_case maybe they should be like addLegal_Foundation or addLegal_foundation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM