Loopback relationship on non id field

∥☆過路亽.° 提交于 2019-12-21 12:57:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!