【问题标题】:Sequelize - Can't set foreign key for row when belongs-to-many association is setSequelize - 设置“属于多”关联时无法为行设置外键
【发布时间】:2021-11-02 00:47:02
【问题描述】:

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

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

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

提前致谢,

我的模型:

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');
    }
}

【问题讨论】:

  • 你能展示你得到的带有指定关联的结果对象吗?
  • 您使用的是哪个版本的sequelize?发这篇文章时的最新版本是 6...
  • sequelize的版本是6.6.5

标签: node.js sql-server express sequelize.js


【解决方案1】:

我所做的就是改变它们的关联方式。在这篇关于many-to-many relatioinships in Sequelize的文章之后,我通过这些关联改变了thm

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'
});

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2012-06-25
    • 1970-01-01
    • 2020-05-15
    • 2018-09-29
    • 1970-01-01
    • 2016-04-30
    • 1970-01-01
    • 2017-05-08
    相关资源
    最近更新 更多