sequelize.js - GetSomething() 在 hasOne 关系中返回错误值,但在 BelongTo 中返回正确值

sequelize.js - GetSomething() returning wrong values in a hasOne relation, but the correct one in a BelongTo

我试图通过我的 CanaisCadastro 中的关系获得 Fluxo,但 GetFluxo() 是 return 错误的行。 如果我在 findOne return 中使用外键正确的值。

async getFluxo(widgetId = 1){
        let canal = await CanaisCadastro.findOne({where: {id_canal_cadastro: widgetId}});
        let fluxo = await canal.getFluxo();
        let fluxo2 = await Fluxo.findOne({where: {id_fluxo: canal.id_fluxo}})
        console.log(
            canal.id_fluxo,  // 8 Value that i wan't
            fluxo.id_fluxo,  // 1 wrong value from GetFluxo
            fluxo2.id_fluxo, // 8 Correct value from findOne
        );
    }

更新

如果我将 .hasOne 替换为 .belongsTo 可以正常工作,但我不明白为什么。

Documentation 表示两者几乎相同:

CanaisCadastro.js:

const { Sequelize, DataTypes, Model } = require('sequelize');
const sequelize = require('../../config/database');
const Fluxo = require('./Fluxo');

class CanaisCadastro extends Model{}

CanaisCadastro.init({
    id_canal_cadastro:{
        type:Sequelize.BIGINT,
        allowNull:false,
        primaryKey:true,
        autoIncrement:true
    },
    descricao_canal:{
        type:Sequelize.STRING,
        allowNull:false,
    },
    id_canal:{
        type:Sequelize.BIGINT,
        allowNull:false
    },
    id_empresa:{
        type:Sequelize.BIGINT,
        allowNull:false
    },
    id_fluxo:{
        type:Sequelize.BIGINT,
        allowNull:false,
        references: Fluxo,

    },


},{
    sequelize,
    modelName:"canais_cadastro",
    freezeTableName:true,
    timestamps:false,
    force:false
})
CanaisCadastro.hasOne(Fluxo, {foreignKey: 'id_fluxo'}); // return wrong values
CanaisCadastro.belongsTo(Fluxo, {foreignKey: 'id_fluxo'}); // Works fine
Fluxo.hasMany(CanaisCadastro, {foreignKey: 'id_fluxo'});
module.exports = CanaisCadastro;

Fluxo.js:

const { Sequelize, DataTypes, Model } = require('sequelize');
const sequelize = require('../../config/database');
class Fluxo extends Model{}

Fluxo.init({
    id_fluxo:{
        type:Sequelize.BIGINT,
        allowNull:false,
        primaryKey:true,
        autoIncrement:true
    },
    descricao:{
        type:Sequelize.STRING,
        allowNull:false,
    },
    id_status:{
        type:Sequelize.BIGINT,
        allowNull:false
    },
    tipo:{
        type:Sequelize.ENUM('Padrão', 'Dialogflow'),
        allowNull:false
    },

},{
    sequelize,
    modelName:"fluxo",
    freezeTableName:true,
    timestamps:false,
    force:false
})

module.exports = Fluxo;

因为 CanaisCadastro 有一个 link 到 Fluxo 使用字段 id_fluxo 这意味着在 Sequelize 方面 CanaisCadastro 属于 Fluxo即取决于它。

记住它们之间的关联应该是:

CanaisCadastro.belongsTo(Fluxo, {foreignKey: 'id_fluxo'});
Fluxo.hasMany(CanaisCadastro, {foreignKey: 'id_fluxo'});