问题
I have two models. Company and Booking.
In the relation part of model Company
"bookings": {
"type": "hasMany",
"model": "Booking",
"foreignKey": "companyId"
}
The issue is, it is possible to post a Booking without companyId which is not ok.
From the explorer.
Booking {
bookingId (string, optional),
name (string),
location (string),
companyId (string, optional)
}
回答1:
You actually can't enforce this particular validation out-of-the-box. Instead you have a couple different options:
a) You can enforce the creation of Booking through company through the endpoint, POST /api/Company/{id}/Bookings
by disabling Booking.disableRemoteMethod('create', ...)
along with any other methods that have the ability to create records from the Booking
model.
b) You can add a remote hook to check whether or not the company record exists and throw an error accordingly.
Booking.beforeRemote('create', function(ctx, booking, next) {
var Company = Booking.app.models.Company;
var companyId = ctx.req.body.companyId;
if (companyId) {
errorMsg = 'Company with id=' + companyId + ' does not exist.';
var noCompany = new Error(errorMsg);
Company.findById(companyId, function(err, company) {
if (err) next(err);
if (!company) {
ctx.res.statusCode = 400;
next(noCompany);
} else {
next();
}
});
} else {
next();
}
});
You will also have to do the same thing for any other endpoints that allow record create such as PUT /api/Bookings
.
Hope that helps!
回答2:
You can add the companyId property explicitly in the booking.json file, and add the required:true property. It would look like
{
"properties": {
"companyId": {
"type": "number",
"required": true
},
... //other properties
}
}
回答3:
In richardpringle's answer part b booking
was an empty object for me.
I was able to get this answer to work by adding app
to the booking.js file like below:
'use strict';
var app = require('../../server/server');
module.exports = function(Booking) {
Booking.beforeRemote('create', function(ctx, booking, next) {
var Company = app.models.Company;
var companyId = ctx.req.body.companyId;
if (companyId) {
errorMsg = 'Company with id=' + companyId + ' does not exist.';
var noCompany = new Error(errorMsg);
Company.findById(companyId, function(err, company) {
if (err) next(err);
if (!company) {
ctx.res.statusCode = 400;
next(noCompany);
} else {
next();
}
});
} else {
next();
}
});
};
- line 2 is new
- line 6 is modified from richardpringle's answer
- From:
var Company = Booking.app.models.Company;
- To:
var Company = app.models.Company;
- From:
来源:https://stackoverflow.com/questions/39080231/how-to-set-relation-foreign-key-to-be-required