我正在尝试使用sequelize创建一个预订系统,并且我必须分开表格。 一间用于客房,一间用于酒店
我想做的,基本上是将房间的 ID 推送到酒店表中名为 rooms 的列中。
它应该能够保存多个id。因此是一个数组。我正在使用 myql,这意味着我已将 rooms 列定义为据我所知的 json。
我只能推送一个 id,但正如我所说,这还不够。
我的房间模型和控制器是这样的
const Room = (sequelize, Sequelize) => {
const Room = sequelize.define("rooms", {
title: {
type: DataTypes.STRING,
allowNull: false,
},
price: {
type: DataTypes.INTEGER,
allowNull: false,
},
maxPeople: {
type: DataTypes.INTEGER,
allowNull: false,
},
desc: {
type: DataTypes.TEXT,
allowNull: false,
},
roomNumbers: {
type: DataTypes.JSON,
allowNull: true,
},
});
return Room;
};
export default Room;
export const createRoom = async (req, res, next) => {
const hotelId = req.params.hotelid;
const newRoom = new Room({
title: req.body.title,
price: req.body.price,
maxPeople: req.body.maxPeople,
desc: req.body.desc,
roomNumbers: {
number: req.body.roomNumbers.number,
unavailableDates: [req.body.roomNumbers.unavailableDates],
},
});
try {
const savedRoom = await newRoom.save();
try {
await Hotel.findOne({
where: {
id: hotelId,
},
}).then((Hotel) => {
Hotel.update({
rooms: savedRoom.id,
});
});
} catch (err) {
next(err);
}
res.status(200).json(savedRoom);
} catch (err) {
next(err);
}
};
如您所见,它推送了保存的房间 ID,但仅推送了单个房间 ID。
我的酒店模型如下所示:
const Hotel = (sequelize, Sequelize) => {
const Hotel = sequelize.define("hotels", {
name: {
type: DataTypes.STRING,
allowNull: false,
},
type: {
type: DataTypes.STRING,
allowNull: false,
},
country: {
type: DataTypes.STRING,
allowNull: false,
},
city: {
type: DataTypes.STRING,
allowNull: false,
},
address: {
type: DataTypes.STRING,
allowNull: false,
},
distance: {
type: DataTypes.STRING,
allowNull: false,
},
photos: {
type: DataTypes.JSON,
allowNull: true,
},
title: {
type: DataTypes.STRING,
allowNull: false,
},
desc: {
type: DataTypes.TEXT,
allowNull: false,
},
rating: {
type: DataTypes.DECIMAL(11, 10),
min: 0,
max: 9,
},
rooms: {
type: DataTypes.JSON,
allowNull: true,
},
cheapestPrice: {
type: DataTypes.DECIMAL(11, 10),
allowNull: false,
},
featured: {
type: DataTypes.BOOLEAN,
default: false,
},
});
return Hotel;
};
export default Hotel;
提前致谢!
在您的 Hotel 模型中, rooms 字段定义为 DataTypes.JSON。如果您想在此字段中存储房间 ID 数组,可以将数据类型更改为 DataTypes.ARRAY(DataTypes.INTEGER)。
rooms: {
type: DataTypes.ARRAY(DataTypes.INTEGER), // Assuming your room IDs are integers
allowNull: true,
}
您还需要确保将新的房间 ID 附加到现有的房间 ID 数组中。
export const createRoom = async (req, res, next) => {
...
try {
const savedRoom = await newRoom.save();
const hotel = await Hotel.findOne({
where: {
id: hotelId,
},
});
// retrieve existing room IDs or initialize an empty array if it doesn't exist yet
const existingRoomIds = hotel.rooms || [];
// add the new room ID to the array
existingRoomIds.push(savedRoom.id);
// call update method on the hotel instance with the new array of room IDs
await hotel.update({
rooms: existingRoomIds,
});
res.status(200).json(savedRoom);
} catch (err) {
next(err);
}
};