我试图弄清楚为什么使用objectionjs orm的koa2后端帖子无法正常运行。设置为使用LoacController的create fucntion的/ loads帖子可以成功地在loads表中创建一个条目,但不会在stops表中创建一个条目,尽管该load模型具有到stop模型的关系映射。 ctx的控制台日志显示:
request:
0|application | { customer_id: '1',
0|application | stops:
0|application | [ { type: 'load', location: '2', time: '2018-07-13T11:43' },
0|application | { type: 'drop', location: '1', time: '2018-07-13T11:43' } ] }
我肯定错过了一些东西...
*****************
/*
* model/Load.js
*/
*****************
const Model = require('../../config/model');
const Stop = require('./Stop');
class Load extends Model {
static get tableName() {
return 'loads';
}
static get relationMappings() {
return {
stops: {
relation: Model.HasManyRelation,
modelClass: Stop,
join: {
from: 'stops.load_id',
to: 'loads.id'
}
},
};
}
}
*****************
/*
* Models/Stop.js
*/
*****************
const Model = require('../../config/model');
const Location = require('./Location');
class Stop extends Model {
static get tableName() {
return 'stops';
}
static get hidden() {
return [
'load_id',
'location_id'
];
}
$formatJson(json) {
json = super.$formatJson(json);
Stop.hidden.forEach(field => delete json[field]);
return json;
}
static get relationMappings() {
return {
location: {
relation: Model.BelongsToOneRelation,
modelClass: Location,
join: {
from: 'stops.location_id',
to: 'locations.id'
}
}
}
}
}
module.exports = Stop;
*****************
/*
* Models/Location.js
/*
*****************
const Model = require('../../config/model');
class Location extends Model {
static get tableName() {
return 'locations';
}
}
module.exports = Location;
*****************
/*
* Controllers/LoadController.js
*/
*****************
const Load = require('../Models/Load.js');
const Stop = require('../Models/Stop.js');
const ApiProblem = require('../Helpers/ApiProblem.js');
const DatabaseError = require('../Helpers/DatabaseError.js');
const ValidateRequest = require('../Helpers/ValidateRequest.js');
class LoadController {
async create(ctx) {
const req = ValidateRequest(ctx, {
'customer_id': 'string|required',
'stops': 'array'
});
console.log('request: ');
console.log(req);
return Load.query().insert(req)
.then(res => {
return ctx.status = 201;
})
.catch(err => {
return DatabaseError(err, ctx);
});
}
}
module.exports = LoadController;