我有两个表:Users和Accounts。一个用户有一个帐户,反之亦然。这是我的两个模型:
用户模型
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const user = sequelizeClient.define('users', {
// omitting the definition for brevity
});
user.associate = function (models) {
user.hasOne(models.accounts);
// I could get things to work when I made it a one to many
// but that's not what I want.
// user.hasMany(models.accounts, { foreignKey: 'user_id' });
};
return user;
};
账户模型
const Sequelize = require('sequelize');
const DataTypes = Sequelize.DataTypes;
module.exports = function (app) {
const sequelizeClient = app.get('sequelizeClient');
const account = sequelizeClient.define('accounts', {
// omitting the definition for brevity
});
account.associate = function (models) {
account.belongsTo(models.users, {foreignKey: 'user_id'});
// I can't get groups and roles working either but that's
// another question...
account.belongsToMany(models.groups, {
through: 'accountsingroups',
foreignKey: 'accountid'
});
account.belongsToMany(models.roles, {
through: 'accountsinroles',
foreignKey: 'accountid'
});
};
return account;
};
从这些模型中,我得到一个Users表和一个Accounts表,其中包含一个名为 的附加列user_id
。
我有一系列创建前的钩子:hashPassword
、hashSecurityQuestions
和relateAccount
. 前两个工作完美无缺。第三个是我遇到问题的地方。这是我的relateAccount
钩子:
创建钩子之前的关联帐户
module.exports = function (options = {}) {
return function (context) {
const AccountModel = context.app.services.accounts.Model;
context.params.sequelize = {
include: [{ model: AccountModel }]
};
};
};
通过上述设置,我可以使用 Postman将新用户插入到Users表中,但Accounts表仍然为空。这是一个示例邮递员请求:
{
"username": "doctordonna",
"firstname": "Donna",
"lastname": "Noble",
"email": "besttempinchiswick@tardis.com",
"password": "ood1!",
"accounts":
{
"questiononeid": "1a3ccccb-42ff-4553-9e54-824022414f50",
"questiononeanswer": "100 words per minute",
"questiontwoid": "6f9b0a38-0b1f-46dd-8726-2c9ff3566686",
"questiontwoanswer": "Adipose Industries",
"questionthreeid": "95c7f66f-63ef-48b2-b2b4-d73d383077e8",
"questionthreeanswer": "Vesuvius",
"questionfourid": "ff94887b-6015-4b84-8259-4801b2b404a3",
"questionfouranswer": "Time Vortex",
"isapproved": true,
"lastactivitydate": null,
"lastlogindate": null,
"lastpasswordchangeddate": null,
"isonline": false,
"islockedout": false,
"lastlockedoutdate": null,
"failedpasswordattemptcount": 0,
"failedpasswordattemptwindowstart": null,
"isdeactivated": false,
"deactivated_at": null
}
}
就像我上面所说的,当我将关联更改为一对多时,它可以完美运行,但是,我希望这是一对一。如果我user.hasOne(models.accounts);
从用户模型中删除,我会收到一条错误消息error: SequelizeEagerLoadingError: accounts is not associated to users!
显然我做错了什么,我想我不理解我在 Sequelize 文档和 Feathers 文档中读到的内容。