[英]Bookshelf, Knex and mysql to save a list of an object
I am very confused to use Bookshelf model to insert data to database in this situation: 在这种情况下,我很困惑使用Bookshelf模型将数据插入数据库:
I am using these libs: knex, bookshelf, express, body-parser, and mysql database 我正在使用以下库:knex,书架,express,body-parser和mysql数据库
I have a table on db is called location, it contains below column: loc_id
, latitude
, longitude
, time
我在db上有一个表,称为location,它包含在下面的列中: loc_id
, latitude
, longitude
, time
This location is sending from one user, so I need to save loc_id
in another table with user_id
此位置是从一个用户发送的,因此我需要使用user_id
将loc_id
保存在另一个表中
to save a location (single object) without saving user_id I use this code: 在不保存user_id的情况下保存位置(单个对象),我使用以下代码:
.post(function (req, res) {
Loc.forge({latitude: req.body.location.lat,
longitude: req.body.location.lng,
date:req.body.time,
speed:req.body.speed,
gpsAnten:req.body.gpsAnten})
.save()
.then(function (location) {
res.json({error: false, data: {id: location.get('id')}});
})
.catch(function (err) {
res.status(500).json({error: true, data: {message: err.message}});
});
});
but now, I am sending post request by body like below from my device:(it is JSON format) 但是现在,我正在通过以下设备按正文发送发布请求:(它是JSON格式)
{
"user_id": 135,
"locations": [
{
"id": 1,
"latitude": "35.374760",
"longitude": "51.5123916",
"date": "0000-00-00 00:00:00"
},
{
"id": 2,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 3,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 4,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 5,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 6,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
}
]
}
How could I save each location in location
table and get this Id, then save its loc_id
and user_id
in loc_user
table ? 如何将每个位置保存在location
表中并获取此ID,然后将其loc_id
和user_id
保存在loc_user
表中?
At least I found the solution to fix this issue; 至少我找到了解决此问题的解决方案; here is my code: 这是我的代码:
.post(function (req, res) {
deviceId = req.body.id
locationArray = req.body.frame;
locationArray.forEach(function(element) {
console.log(element);
Loc.forge({latitude: element.location.lat,
longitude: element.location.lng,
date: element.time,
speed: element.speed,
gpsAnten: element.gpsAnten})
.save()
.then(function (location) {
userDevice.forge({
device_id: deviceId,
location_id: location.get('id')
})
.save()
.then(function(middleware) {
console.log('Save middleware');
})
.catch(function(err) {
console.log('Error middleware:' + err.message);
})
})
.catch(function (err) {
console.log('Error location:' + err.message);
});
});
});
It is not as clear as I need but seems is only solution. 这不是我需要的那么清晰,但似乎只是解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.