blockwork
blockwork

Reputation: 197

Loopback relationship on non id field

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,

Upvotes: 6

Views: 2525

Answers (2)

ffflabs
ffflabs

Reputation: 17481

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.

Upvotes: 0

user4081481
user4081481

Reputation:

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.

Upvotes: 1

Related Questions