I Have Events model and this model there is Speakers and Attendees, Attendees and Speakers are users in the application.
how i can do it with relation in LoopBack? like: get event with his speakers and attendees
and how i can assign Attendee to event?
An Event could have one/Many speakers and many attendees, so the event relation should be like below
event.json
"relations": {
"speakers": {
"type": "hasMany",
"model": "Speaker",
"foreignKey": ""
},
"attendees": {
"type": "hasMany",
"model": "Attendee",
"foreignKey": ""
}
}
The speaker belongsTo to an event :
speaker.json
"relations": {
"event": {
"type": "belongsTo",
"model": "Event",
"foreignKey": ""
}
}
and finally an attendee belongs to an event
attendee.json
"relations": {
"event": {
"type": "belongsTo",
"model": "Event",
"foreignKey": ""
}
}
Putting the relations above will give you new endpoints in your explorer, now you can assign an attendee to an event using the POST method like below.
PS: Do not create the Attendee ID since the idInjection is TRUE so it will be created automatically just assign the eventId
{
"name": "string",
"id": "string",
"eventId": "string"
}
Note that you don't have to create a foreign key since loopback will target the default id of each related model only if you need to use custom ones.
UPDATE
To make it work on the built in USER Model, we should extend it first.
To extend the user model we should create a new one :
slc loopback:model
Once the model is created, edit the config-model.json and disable the built in User model.
Add this property to User : "public": false
(this will disable User from being shwon in the explorer)
"User": {
"dataSource": "MongoDs",
"public": false
}
Add Relation in event.json with the new user model
"relations": {
"users": {
"type": "hasMany",
"model": "user",
"foreignKey": ""
}
}
Add Relation user.json with Event model
"relations": {
"event": {
"type": "belongsTo",
"model": "Event",
"foreignKey": ""
}
Now you can assign a user to an event. However to assign a speaker or an attendee you should create type field like "type" : { "type": "string"}
which could be "attendee"
/ "speaker"
To find users from your event model use this filter : {include: 'users'}
in your find()
function.