使用adonisjs插入多行时出现问题。我在json数组中有一个表单数据,当我尝试使用request.post
插入此数据以获取数组索引时,它不起作用
这是我在json数组中的数据示例:
[
{
"id_cart" : "1",
"id_product" : "1",
"shop_id" : "2",
"price" : "10000"
},
{
"id_cart" : "1",
"id_product" : "2",
"shop_id" : "3",
"price" : "20000"
}
]
然后这是我的控制器:
const id_cart = nanoid(25)
const detailInfo = request.post(['id_cart','id_product','shop_id','price'])
const detail = new Detail()
detail.id_cart = id_cart
detail.id_product = detailInfo.id_product
detail.shop_id = detailInfo.shop_id
detail.price = detailInfo.price
await detail.save()
列id_product, shop_id, and price
的结果为 空 。我的代码有什么问题?
答案 0 :(得分:1)
像这样设置JSON
输入的格式
{
"products": [
{
"id_cart": "1",
"id_product": "1",
"shop_id": "2",
"price": "10000"
},
{
"id_cart": "1",
"id_product": "2",
"shop_id": "3",
"price": "20000"
}
]
}
按以下步骤插入数据库:
const productList = request.input("products");
await Product.createMany(productList);
答案 1 :(得分:0)
id_product,shop_id和price列的结果为空。我的代码有什么问题?
因为结果有几个对象。
您可以使用Request collection:
// Example from official documentation
const users = request.collect(['username', 'age'])
// output
[{ username: 'virk', age: 26 }, { username: 'nikk', age: 25 }]
// save to db
await User.createMany(users)
获取完整结果并循环处理
const detailInfo = request.all() //Array
并创建foreach
detailInfo.rows.forEach(async (info) => {
...
})