Search code examples
loopbackjsstrongloophas-one

Strongloop - hasOne relation


I am having some trouble with setting up a hasOne relation, which probably comes from me understanding the relation wrongly?

I have 2 Models, one user model, and one location model. What I want to add now is a relation between user and location, meaning a user has a current location. But if I set up a hasOne relation on the user model with the location, I end up with a userId property in the location. But this is completely wrong, since several users can have the same current location, so the user model should store the location id, not the location the user id. So how can I achieve what I want, so that I can afterwards query the user and include the current location?

I can of course add a property to the user and store the id of the location there, but then I can't as easily include the location in a user request. So I would prefer using relations to achieve this.


Solution

  • Your problem is a bit unclear, given the comments of Brian's post, but if you absolutely need Users to share a given set of locations then you would be better off using User belongsTo location.

    This will create a locationId field in User, and you will be able to GET api\Users\{userId}\location

    Eventually, you can set a location hasMany User to retrieve from a given location all the users in there