问题描述
我将knex与异议js一起使用,并且我想同时插入带有roomImage表的roomType表,因为表roomType有很多roomImage 这是我的数据库
.createTable(tableName.roomImage,(table) => {
table.increments('id').notNullable()
table.string('imageUrl').notNullable()
}).createTable(tableName.roomType,(table) => {
table.increments('id').notNullable()
table.string('type').notNullable()
table.string('description').notNullable()
table.float('price').notNullable()
table.integer('bed').notNullable()
table.integer('image_id').references('id').inTable(tableName.roomImage)
})
这是我的模特
const { Model } = require('objection')
const tableNames = require('../../constants/tablename')
class Image extends Model {
static get tableName() {
return tableNames.roomImage
}
static get idColumn() {
return 'id'
}
}
class RoomType extends Model {
static get tableName() {
return tableNames.roomType
}
static get idColumn() {
return 'id'
}
static get relationalMapping() {
return {
imageUrl: {
relation: Model.HasManyRelation,modelClass: Image,join: {
from: "roomType.image_id",to: 'roomImage.id'
}
}
}
}
}
module.exports = RoomType
这是我的代码
router.post('/create',async (req,res,next) => {
const { type,price,bed,description,roomImage } = req.body
try {
await schema.validate(req.body,{
abortEarly: false
})
const existRoomType = await RoomType.query().findOne({ type }).first()
if (existRoomType) {
res.status(400).json({ message: 'This role already exist' })
} else {
const tx = await RoomType.transaction(async trx => {
const data = await RoomType.query(trx).insertGraph({
type,roomImage
},{ relate: true })
res.json({ data })
})
console.log(roomImage);
res.json({ data })
}
} catch (e) {
next(e)
}
})
这是我要插入的json主体,我想将许多图像插入到roomtype表中 enter image description here
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)