【问题标题】:sequelize hasOne how to access relationship?sequelize hasOne如何访问关系?
【发布时间】:2021-04-25 13:21:11
【问题描述】:

如何访问 hasOne 关系,它返回 undefined。我遵循文档。我想,已经对了。很难找到逐步讨论关系的教程。我看到文档在模型中使用 get。比如getTag。

应用程序

const media = await Media.findOne();
console.log(media.Tag); 

媒体模型

const Tag = require('./tag');
Media.init({
    id: {
        type: DataTypes.BIGINT.UNSIGNED,
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        unique: true
    },
    type_id: {
        type: DataTypes.TINYINT.UNSIGNED,
        allowNull: false,
        references: {
            model: 'types',
            key: 'id'
        }
}, {
    sequelize,
    modelName: 'Media',
    tableName: 'media',
    engine: 'MYISAM',
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci',
    timestamps: false 
});

Media.hasOne(Tag, {
    as: 'Tag',
    foreignKey: 'type_id'
});

标签模型

Tag.init({
    id: {
        type: DataTypes.MEDIUMINT.UNSIGNED,
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        unique: true
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false
    }
}, {
    sequelize,
    modelName: 'Tag',
    tableName: 'tags',
    engine: 'MYISAM',
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci',
    timestamps: false 
});

【问题讨论】:

  • doc 通过包含在 findall/one 中。你必须包括你的关系模型

标签: sequelize.js


【解决方案1】:

您需要在查询中use the include property 让 Sequelize 知道您要从关系中获取数据。因为关系层次结构可能非常广泛,每次都加载它们并不是有效的,所以你需要告诉 Sequelize 你想要加载什么do。您可以使用attributes 属性进一步优化,只获取您需要的字段(默认返回全部)。

const media = await Media.findOne({
  include: {
    model: Tag,
  },
  where: 
    // ... your criteria
  },
});

console.log(media.Tag); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 2020-10-06
    • 1970-01-01
    • 2014-07-02
    相关资源
    最近更新 更多