Sequelize HasMany 不起作用

问题描述 投票:0回答:3

我在我的 sails.js 应用程序中使用 sails-hook-sequelizesails-hook-sequelize-blueprints

我有一个模型叫

Site

module.exports = {

    attributes: {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: Sequelize.STRING,
            required: true
        }
    },
    associations: function() {
        Site.hasMany(Templates, {
            as: 'templates'
        });
    }
};

每个站点都有多个与其关联的

Templates

module.exports = {

    attributes: {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: Sequelize.STRING,
            required: true
        }
    }
};

我收到一条错误消息

/user/myproject/node_modules/sails-hook-sequelize-blueprints/index.js:362
              var alias = foreign.as || foreign.name || foreign;
                                 ^

TypeError: Cannot read property 'as' of undefined

知道它可能是什么吗?

node.js orm sails.js sequelize.js
3个回答
1
投票

您需要将

foreignKey
添加到
hasMany
定义中:

    Site.hasMany(Templates, {
        as: 'templates',
        foreignKey: 'SiteId'
    });

并将

belongsTo
关联添加到
Templates
模型定义中:

    Templates.belongsTo(Site) // this will add SiteId to the Templates table

与您的命名保持一致也是一个很好的做法 - 模型名称应该是单数(

Template
而不是
Templates
),并且这些关系及其后续方法将更加不言自明。 Sequelize 将在有意义的地方进行复数化(即您正在处理许多实例)。


0
投票

我遇到了同样的问题,然后出现错误:

TypeError: Cannot read properties of undefined (reading 'name')

问题在于我如何加载模型以进行特定测试。我只加载了我拥有的所有模型中的 2 个:

// Initialize Sequelize
const sequelize = new Sequelize("sqlite::memory:", { logging: console.log });

// Initialize models
User.initModel(sequelize);
Credit.initModel(sequelize);

// Set up associations
User.associate();
Credit.associate();

// Sync models with database
await sequelize.sync({ force: true });

解决方案是加载所有这些,因为

User
有更多的关联,而不仅仅是
Credits
:

export function initModels(sequelize: Sequelize) {
  User.initModel(sequelize);
  Credit.initModel(sequelize);
  Wallet.initModel(sequelize);
  Transaction.initModel(sequelize);
  Round.initModel(sequelize);
  RoundResult.initModel(sequelize);
  Prompt.initModel(sequelize);
  TextToImg.initModel(sequelize);

  User.associate();
  Credit.associate();
  Wallet.associate();
  Transaction.associate();
  Round.associate();
  RoundResult.associate();
  Prompt.associate();
  TextToImg.associate();

  return {
    User,
    Credit,
    Wallet,
    Transaction,
    Round,
    RoundResult,
    Prompt,
    TextToImg,
  };
}

然后在我的测试中:

// Initialize Sequelize
const sequelize = new Sequelize("sqlite::memory:", { logging: false });

initModels(sequelize);

await sequelize.sync({ force: true });

-1
投票

如前所述,这是因为您的变量“foreign”未定义,并且您尝试读取未定义的属性。

© www.soinside.com 2019 - 2024. All rights reserved.