Sequelize - 设置属于多关联时无法为行设置外键

Sequelize - Can't set foreign key for row when belongs-to-many association is set

大家好 我正在使用 sequelize 库来管理 express-react 项目中的 SQL 服务器数据库。当我尝试通过一个名为 'autoridad_juicio' 的 table 将两个名为 'juicios_amparo''autoridades_responsables' 的 table 关联到多对多关系时,问题就出现了,这我已经创建并填充了数据,以加入这两者。

当我想将 'autoridades_responsables' table 中的注册表关联到 'juicios_amparo' table 时,问题就来了。我尝试使用 sequelize 定义的 mixin 和特殊方法,将它们称为 'setAutoridad_responsable()' 和其他配置(我很难理解它们如何设置方法名称)。通过联合 table 'autoridad_juicio' 调用 table,将两个 belogsToMany() 关联更改为 hasMany() 为两个 table 甚至设置具有 id 的新注册表也无法正常工作。

有没有办法设置这两个 table 具有 N:M 关系,使用这些方法在执行 juicioAmparo.findAll({ include: 'autoridad_responsable' }) 时将 'autoridades_responsables' 检索到 'juicios_amparo'查询?

提前致谢,

我的模特:

jucioAmparo.js

import sequelize_pkg from 'sequelize';
import sequelize from '../database/connection.js';
import Usuario from '../models/Usuario.js';

const { Model, DataTypes } = sequelize_pkg;

class juicioAmparo extends Model{
    static classLevelMethod() {
        return 'foo';
    }
    instanceLevelMethod() {
        return 'bar';
    }
    getFullname() {
        return [this.firstname, this.lastname].join(' ');
    }
}

juicioAmparo.init({
    id_juicio_amparo: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
        unique: true
    },
    id_autor: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false,
        references: {
            // modelo de referencia del FK
            model: Usuario,
            // Nombre de la columna del ID del FK
            key: 'id_usuario'
            
        }
    },
    fecha_registro: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        allowNull: false,
    },
    fecha_expedicion: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        allowNull: false,
    },
    numero_amparo: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    quejoso: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    juzgado: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    actos_reclamados: {
        type: DataTypes.STRING,
        allowNull: false
    },
    fecha_informe: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        allowNull: true,
    },
    resolucion_incidente: {
        type: DataTypes.STRING,
        allowNull: true,
    },
    resolucion_principal: {
        type: DataTypes.STRING,
        allowNull: true,
    },
    fecha_interposicion_recursos: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        allowNull: true,
    },
    recursos: {
        type: DataTypes.STRING,
        allowNull: true,
    },
    resolucion_recurso: {
        type: DataTypes.STRING,
        allowNull: true,
    },
    ejecutoria: {
        type: DataTypes.DATE,
        defaultValue: DataTypes.NOW,
        allowNull: true,
    },
    observaciones: {
        type: DataTypes.TEXT,
        allowNull: true,
    },
    estado: {
        type: DataTypes.STRING,
        allowNull: true,
    },
}, {
    sequelize,
    modelName: 'juicioAmparo',
    tableName: 'juicios_amparo',
    paranoid: true,
    deletedAt: 'deleted_at',
    indexes: [{ unique: true, fields: ['id_juicio_amparo'] }]
})

export default juicioAmparo;

AutoridadJuicio.js

import sequelize_pkg from 'sequelize';
import sequelize from '../database/connection.js';
import juicioAmparo from "./juicioAmparo.js";
import CatAutoridadResponsable from "./CatAutoridadResponsable.js";

const { Model, DataTypes } = sequelize_pkg;

class Autoridad_Juicio extends Model{
    static classLevelMethod() {
        return 'foo';
    }
    instanceLevelMethod() {
        return 'bar';
    }
    getFullname() {
        return [this.firstname, this.lastname].join(' ');
    }
}
Autoridad_Juicio.init({
    id_union_autoridad_juicio: {
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false,
        primaryKey: true,
        autoIncrement: true,
        unique: true
    },
    id_autoridad:{
        type: DataTypes.INTEGER.UNSIGNED,
        allowNull: false,
        references: {
            // modelo de referencia del FK
            model: CatAutoridadResponsable,
            // Nombre de la columna del ID del FK
            key: 'id_cat_autoridad_responsable'
            
        }
    },
    id_juicio:{
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            // modelo de referencia del FK
            model: juicioAmparo,
            // Nombre de la columna del ID del FK
            key: 'id_juicio_amparo'
            
        }
    }
}, {
    sequelize, modelName: 'Autoridad_Juicio', tableName: 'autoridad_juicio',
    //creando indexes
    indexes: [{ unique: true, fields: ['id_union_autoridad_juicio'] }]
})

export default Autoridad_Juicio;

CatAutoridadResponsable.js

import sequelize_pkg from 'sequelize';
import sequelize from '../database/connection.js';

const { Model, DataTypes } = sequelize_pkg;

class CatAutoridadResponsable extends Model{
    static classLevelMethod() {
        return 'foo';
    }
    instanceLevelMethod() {
        return 'bar';
    }
    getFullname() {
        return [this.firstname, this.lastname].join(' ');
    }
}
CatAutoridadResponsable.init({
    id_cat_autoridad_responsable: {
        type: DataTypes.INTEGER.UNSIGNED,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false,
        unique: true
    },
    autoridad_responsable:{
        type: DataTypes.STRING,
        allowNull: false,
    },
    ubicacion:{
        type: DataTypes.STRING,
        allowNull: false,
    },
}, {
    sequelize, modelName: 'CatAutoridadResponsable', tableName: 'cat_autoridades_responsables',
    //creando indexes
    indexes: [{ unique: true, fields: ['id_cat_autoridad_responsable'] }]
})

export default CatAutoridadResponsable;

Associations.js

import Autoridad from '../models/CatAutoridadResponsable.js';
import juicioAmparo from '../models/juicioAmparo.js';
import Autoridad_Juicio from './Autoridad_Juicio.js';


export const crear_asociaciones = (activado) => {
    if(activado === true){
        console.log('----------> Creando asociaciones <----------');

        Autoridad.belongsToMany(juicioAmparo, { 
            as: 'autoridadjuicio',
            through : Autoridad_Juicio,
            foreignKey: 'id_autoridad', // replaces `categoryId`
            otherKey: 'id_juicio_amparo' // replaces `productId`
        });

        juicioAmparo.belongsToMany(Autoridad, { 
            as: 'autoridadjuicio',
            through : Autoridad_Juicio,
            foreignKey: 'id_juicio_amparo', // replaces `categoryId`
            otherKey: 'id_autoridad' // replaces `productId`
        });

        //These are the previous associations I've tried, with no success
        //
        // Autoridad_Juicio.hasMany(CatAutoridadResponsable, { 
        //     as: 'autoridades',
        //     foreignKey: 'id_cat_autoridad_responsable',
        // });

        // Autoridad_Juicio.hasMany(juicioAmparo, { 
        //     as: 'juicios',
        //     foreignKey: 'id_juicio_amparo',
        // });

        // CatAutoridadResponsable.belongsTo(Autoridad_Juicio, { 
        //     as: 'autoridades',
        //     foreignKey: 'id_cat_autoridad_responsable',
        // });

        // juicioAmparo.belongsTo(Autoridad_Juicio, {
        //     as: 'juicios', 
        //     foreignKey: 'id_juicio_amparo',
        // });

        console.log('----------> Asociaciones creadas <----------');
    } else {
        console.log('>> Asociaciones omitidas');
    }
}

我所做的修复是改变它们的关联方式。在这篇关于 many-to-many relatioinships in Sequelize

的文章之后,我通过这些关联更改了它们
Acto.belongsToMany(juicioAmparo, { 
    as: 'JuiciosPorActo',
    through: 'Acto_Juicio',
    foreignKey: 'id_acto_reclamado' 
}); 
juicioAmparo.belongsToMany(Acto, { 
    as: 'ActosPorJuicio',
    through: 'Acto_Juicio',
    foreignKey: 'id_juicio_amparo' 
}); 
        
Acto_Juicio.belongsTo(Acto, { 
    targetKey: 'id_acto_reclamado',
    foreignKey: 'id_acto_reclamado',
    as: 'ActosReclamados'
});

Acto_Juicio.belongsTo(juicioAmparo, { 
    targetKey: 'id_juicio_amparo',
    foreignKey: 'id_juicio_amparo',
    as: 'Juicios'
});