NodeJS 将数据插入深度嵌套关系

hivapdat  于 2023-01-20  发布在  Node.js
关注(0)|答案(1)|浏览(130)

我目前是Adonis Js的新手,我很难将数据插入更深层次的关系中。
假设我有3个表,国家,城市,商店国家有很多城市,城市有很多商店,那么如果我插入很多数据,比如我有1个国家,5个城市,20个商店,有什么简单的方法可以解决这个问题吗?

const country = request.input('country') *//this is the name of the country separated from the* array
const data = request.input('data') *//so this one is an array, and has nested arrays in it*

"所以基本上我所做的是"

try{
const country = await Country.create({
 name: country
},{client: trx })

await country.related('cities').updateOrCreateMany(data, 'name')

await country.load('cities')

const serializedCountry = country.serialize()
const savedCountry = serializedCountry.cities

let index = 0
while (index < savedCountry.length){
    const queryCountry = await Country.query({ client: trx }).where({ id: savedCountry[index].id }).first()

await queryCountry.related('shops').updateOrCreateMany(data[index].shops, 'name')
index++

const res = await Country.query().preload('cities', (q) => q.preload('shops')

await trx.commit()

return response.status(200).json({message: 'saved', data: res })
}catch(error){
 await trx.rollback
}

这不是我真实的的代码,但这是基本的想法。2但我想学的是一个简单的方法,而不是这样做。
如果有答案的话会很有帮助。非常感谢

tf7tbtn2

tf7tbtn21#

const trx = await Database.transaction()
  try {
    const name = request.input('country')
    const data = request.input('data')

    const country = new Country()
    country.name = name
    country.useTransaction(trx)
    await country.save()

    let cityIndex = 0
    while (cityIndex < data.length) {
      const city = new Cities()
      city.countryId = country.index
      city.name = data.name
      city.useTransaction(trx)
      await city.save()

      let shopIndex = 0
      shopData = data[cityIndex].shop
      while (shopIndex < shopData.length) {
        const shop = new Shops()
        shop.cityId = city.id
        shop.name = shopData[shopIndex].name
        shop.useTransaction(trx)
        await shop.save()
          
        shopIndex++
      }
      cityIndex++
    }

    await trx.commit()

    await country.load('cities', query => query.preload('shops'))

    return response.status(200).json({ message: 'saved', data: country })
  } catch {
    await trx.rollback()`enter code here`
    return response.status(500).json({ message: 'whoops' })

相关问题