0

I have a Loopback API with a user that is a model with a base class of User.

I also have another model called participant. This represents a user that has signed up to participate in an event.

I want this Participant to require a a reference to a user (foreign key). I also want it so that the user can only create ONE Participant. Lastly, when a user creates a Participant, it has to reference the users own ID. How can I set this up?

Alex
  • 731
  • 1
  • 11
  • 24

1 Answers1

0

This seems like standard one-to-one connection to me. Loopback provides HasOne and BelongsTo relations for this purpose.

Given your scenario, you can define Participant and MyUser as follows:

my-user.json

{
  "name": "MyUser",
  "base": "User",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {},
  "remoting": {
    "normalizeHttpPath": true
  },
  "validations": [],
  "relations": {
    "participant": {
      "type": "hasOne",
      "model": "Participant",
      "foreignKey": "userId"
    }
  },
  "acls": [],
  "methods": {},
  "mixins": {}
}

participant.json

{
  "name": "Participant",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {},
  "validations": [],
  "relations": {
    "user": {
      "type": "belongsTo",
      "model": "MyUser",
      "foreignKey": "userId"
    }
  },
  "acls": [],
  "methods": {}
}

Then you can create a Participant for your MyUser like this:

POST /my-users/{id}/participant

If you try to create another Participant instance for this MyUser instance, you will get a following error:

Error (500): HasOne relation cannot create more than one instance of Participant

Ivan Schwarz
  • 814
  • 1
  • 14
  • 22