问题
I want to specify the relationship betweet 2 mssql tables. Paymentcategory and Payout. paymentcategory.id joins on the payout.category column.
in payout.json model I specified as foreignKey: id,
"relations": {
"paymentcategories": {
"type": "hasOne",
"model": "Paymentcategory",
"foreignKey": "id"
}
but loopback looks by default for the id field as primaryKey
Is there a way to specify the join on the category field. Preferably in the common/models/payout.json file?
"relations": {
"paymentcategories": {
"type": "hasOne",
"model": "Paymentcategory",
"foreignKey": "id",
"primaryKey": "category" ??????????????????
}
Now I get this error:
"error": {
"name": "Error",
"status": 400,
"message": "Key mismatch: Paymentpayout.id: undefined, Paymentcategory.id: 1",
"statusCode": 400,
回答1:
You can defined your foreign key to be whatever you want (in /common/models/your-model-name.json
.
See my example at https://github.com/strongloop/loopback-example-relations-basic for more info.
回答2:
Your Paymentcategory model should be
{
"name":"Paymentcategory",
"options":{...},
"properties":{
"id":{...},
...
},
"relations":{
"payouts":{
"type":"hasMany",
"model":"Payout",
"foreignKey":"category"
}
}
}
note that one payout category might have N payouts with that category (that's what categorizing is for).
Your Payout model should be
{
"name":"Payout",
"options":{...},
"properties":{
"id":{...},
"category":{...},
...
},
"relations":{
"paymentcategories":{
"type":"belongsTo",
"model":"Paymentcategory",
"foreignKey":"category"
}
}
}
Important to note is: both relation objects have the same foreignKey, and it's Payout.category.
来源:https://stackoverflow.com/questions/26802071/loopback-relationship-on-non-id-field