在不同的项目中,我一直坚持一个非常基本的想法。
每次,都是同样的担忧。我想向关联中添加一条新记录,但在没有主键的情况下获取父项。
例如,让我们以api/models/car.js模型为例:
module.exports = {
attributes: {
licensePlate: {
type: 'integer',
required: true,
unique: true
},
locations: {
collection: 'location',
via: 'car'
}
}
};
还有一个api/models/location.js模型:
module.exports = {
attributes: {
coordinates: {
type: 'array',
required: true
},
car: {
model: 'car'
}
}
};
一辆车可以有多个位置,一个位置只有一辆车。
我可以使用本机addTo
蓝图操作向汽车添加位置
POST /car/1/locations
{"coordinates":[2.13654,50.323654]}
现在,如果出于某种原因,我无法访问汽车标识符,并且想使用另一个字段,例如唯一的 licensePlate 怎么办?
基本上,我会在config/routes中创建一个自定义路由,比如
POST /car/byplate/:licensePlate/locations': {
controller: 'Car',
action: 'addLocationByPlate'
}
为了能够打电话
POST /car/byplate/AW45RE65/locations
{"coordinates":[2.13654,50.323654]}
这就是问题所在......打开我全新的动作控制器,我意识到,尽管按板选择我的汽车,但以下逻辑(验证、位置创建、位置创建发布、位置添加到汽车的位置集合、位置添加发布,错误处理)已经在sails.js 核心中实现。
所以这是一个问题:
如何使用自定义路由正确调用本机蓝图操作?