在 Adonisjs 中插入多行不起作用
Insert multi rows in Adonisjs doesn't work
我在使用 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
列的结果是 null。我的代码有什么问题?
The result of column id_product, shop_id, and price is null. What's wrong with my code?
因为结果有几个对象。
您可以使用 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) => {
...
})
像这样格式化你的 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);
我在使用 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
列的结果是 null。我的代码有什么问题?
The result of column id_product, shop_id, and price is null. What's wrong with my code?
因为结果有几个对象。
您可以使用 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) => {
...
})
像这样格式化你的 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);