DaafVader
DaafVader

Reputation: 1754

Loopback referencesMany nested foreign key

I want to reference a different model(as discribed here: https://loopback.io/doc/en/lb2/Embedded-models-and-relations.html) but the by a nested id:

{
 "name" : "person",
 ...
  "relations": {
    "cars": {
      "type": "referencesMany",
      "model": "car",
      "foreignKey": "cars.id"
  }
}

Person json will actually be something like:

{
  ...
  cars: [{"id": 1, "name": "car1"}, ...]
}

And car model will be the full car details

Do I have to write my own remote method to do this?

Upvotes: 2

Views: 628

Answers (1)

veakey
veakey

Reputation: 26

Yosh DaafVader,

I've came accross this issue also and took time to find a solution ^^ but actually you just have to play with the parameter options inside your target relation property. The documentation states how the relation should be defined (sure the loopback cli does not include in version 3.x yet the way to use embeds nor references).

In your person model you have to change the foreignKey and to add the following options to be able to only use id to reference cars.

{
 "name" : "person",
 ...
  "relations": {
    "cars": {
      "type": "referencesMany",
      "model": "car",
      "foreignKey": "",
      "options": {
        "validate": true,
        "forceId": true
      }
  }
}

Now you will be able to see in the explorer the new routes to add, remove and see the cars that belongs to the target person.

[Edit]

  1. the foreignKey shall be blank, in order to be able to add items properly in the list of cars, or you can test and give some feedbacks about it
  2. The validate option ensures the id exists in your database
  3. forceId option will ensure it accepts only ids as a parameter

[/Edit]

Hope it will help :)

Cheers

Upvotes: 1

Related Questions