【发布时间】:2020-10-08 02:51:40
【问题描述】:
我正在创建一个旅行计划应用程序。我想使用的模型是用户、旅行、活动和租赁。
这就是我打算将它们关联起来的方式:
一个用户可以有许多旅行、活动和租赁
许多旅行可以有许多活动和租赁
很多活动可以有很多租用
在我的节点服务器中,我创建了一个具有以下 Sequelize 关联的数据库文件:
User = sequelize.import('./models/user')
Trip = sequelize.import('./models/trip')
Activity = sequelize.import('./models/activity')
Rental = sequelize.import('./models/rental')
Activity.belongsTo(User)
User.hasMany(Activity, { as: 'Activities' })
Rental.belongsTo(User)
User.hasMany(Rental, { as: 'Rentals' })
Activity.belongsTo(Trip)
Trip.hasMany(Activity, { as: 'Activities' })
Rental.belongsTo(Trip)
Trip.hasMany(Rental, { as: 'Rentals' })
Rental.belongsTo(Activity)
Activity.hasMany(Rental, { as: 'Rentals' })
这是我的模型:
用户
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('user', {
firstName: {
type: DataTypes.STRING,
allowNull: false
},
lastName: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
isAdmin: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
})
return User;
}
旅行
module.exports = (sequelize, DataTypes) => {
const Trip = sequelize.define('trip', {
title: {
type: DataTypes.STRING,
allowNull: false
},
departLoc: {
type: DataTypes.STRING,
allowNull: false
},
arrivalLoc: {
type: DataTypes.STRING,
allowNull: false
},
startDate: {
type: DataTypes.DATE,
allowNull: false
},
endDate: {
type: DataTypes.DATE,
allowNull: false
},
travelMethod: {
type: DataTypes.STRING,
allowNull: true
},
reason: {
type: DataTypes.STRING,
allowNull: true
},
description: {
type: DataTypes.STRING,
allowNull: true
}
})
return Trip;
}
活动
module.exports = (sequelize, DataTypes) => {
const Activity = sequelize.define('activity', {
title: {
type: DataTypes.STRING,
allowNull: false
},
startDate: {
type: DataTypes.DATE,
allowNull: false
},
endDate: {
type: DataTypes.DATE,
allowNull: false
},
description: {
type: DataTypes.STRING,
allowNull: true
}
})
return Activity;
}
出租
module.exports = (sequelize, DataTypes) => {
const Rental = sequelize.define('rental', {
agency: {
type: DataTypes.STRING,
allowNull: false
},
item: {
type: DataTypes.STRING,
allowNull: false
},
startDate: {
type: DataTypes.DATE,
allowNull: false
},
endDate: {
type: DataTypes.DATE,
allowNull: false
},
description: {
type: DataTypes.STRING,
allowNull: true
}
})
return Activity;
}
但是,当我检查我的 pgadmin 时,我看到了
- 我的活动表有 userId、tripId 和一个不必要的 activityId 列
- 我的出租桌与它没有任何关联。
每当我尝试在这些模型中插入新条目时,都会收到如下错误:
如何关联我的表以获得所需的关联?
【问题讨论】:
标签: sql node.js sequelize.js