我有三种型号试图定义它们之间的关系。
模型:用户支付债务人
- 用户有很多付款
- 付款属于用户
- 付款有许多债务人
- 债务人属于付款
- 债务人属于付款
我需要定义源和目标中的关系吗?即
User.hasMany(Payment, {as: 'Payments'})
以及
Payment.belongsTo(User)
,还是可以在一个模型中定义它?
尝试在两者中定义它时似乎会遇到错误。我导入的模型是 undefined
,因此,当我尝试将其传递到" allatesto()"或" hasmany()"函数时,我会得到错误 called with something that's not an instance of Sequelize.Model
当我仅将其包含在一个模型中时,它无法正确创建关系。
我的模型如下:
付款模型:
import { sequelize } from '../config';
import Sequelize from 'sequelize';
import User from './User';
const Payment = sequelize.define('payment', {
amount: {
type: Sequelize.FLOAT
},
reference: {
type: Sequelize.STRING
},
user_id: {
type: Sequelize.INTEGER
}
});
Payment.belongsTo(User)
export default Payment;
用户模型:
import { sequelize } from '../config';
import Sequelize from 'sequelize';
import Payment from './Payment';
const User = sequelize.define('user', {
email: {
type: Sequelize.STRING
},
username: {
type: Sequelize.STRING
},
firstName: {
type: Sequelize.STRING
},
lastName: {
type: Sequelize.STRING
},
facebookID: {
type: Sequelize.STRING
}
});
User.hasMany(Payment, {as: 'Payments'})
export default User;
//编辑
尝试使用付款创建新用户时,我会得到错误payment is not associated to user!
exports.create = (req, res) => {
User.create({
email: 'test3@gmail.com',
firstName: "Test",
lastName: "Test",
username: 'fnord',
payment: [
{ amount: 10.00},
]
}, {
include: [ Payment ]
})
}
发生的,因为在payment
中,您需要User
模型和VICE-vices-vice-vessa,在user
中,您需要Payment
(圆形依赖关系)。为了避免这种情况
module.exports = (sequelize, DataTypes) => {
return sequelize.define('modelName', {
// attributes
}, {
// additional options, like classMethods in which you could create the association
classMethods: {
associate: function(models) {
this.belongsTo(models.Model);
this.hasMany(models.Model);
}
}
});
}
为了实现它,您必须使用sequelize-cli
模块。如果安装它,则可以使用sequelize init
命令,该命令将生成一个文件,该文件将所有模型注册到续集(所有这些模型最初都位于一个位置,但是您可以通过修改自动生成的文件来更改它)。
在这种情况下,在每个模型上进行迭代,对其进行注册(使用sequelize.import()
方法),并调用associate
函数,该函数在模型之间创建关系。这样可以防止您提到的情况。
如果某人在像我这样的续集协会中挣扎,这可能会对您有所帮助,因为在文档中没有提到任何内容,如果您使用Sequelize.define
,您也面临着您的关系。一个问题,为我做了这项工作
'use strict';
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
},
name: {
type: DataTypes.STRING
},
email: {
type: DataTypes.STRING,
unique : true,
},
password: {
type: DataTypes.STRING
},
status: {
type: DataTypes.STRING
},
});
let Bookmark = sequelize.model('Bookmark');
User.hasMany(Bookmark,{foreignKey : 'user_id', as 'bookmarks'});
return User;
};
希望它有效!