I using knex with objection js and i want to insert to roomType table with roomImage table at the same because table roomType has many roomImage This my database
.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)
})
This is my model
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
This is my code
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, price, bed, description, roomImage
}, { relate: true })
res.json({ data })
})
console.log(roomImage);
res.json({ data })
}
} catch (e) {
next(e)
}
})
This is the json body that i want to insert, I want to insert many image into roomtype table enter image description here