Search code examples
reststronglooplookup-tablesloopback

Query Reference/lookup values in LoopBack


How do you query reference/lookup data and what is the correct relation to build between models to support them?

Example:

Address model has a field that represents the city the address is located. A city model has a pre-populated list of cities. I want to build a loopback relation between the two models such that I can reference a city when adding a new address and when querying an address return the city as part of the address.

In a relational db you could have a foreign key lets say CityId that is populate with the reference to the city. You could then query the Address table and include a join to the city table to return the city related to the address.

In loopback I have the following models (cut down for the example):

Address Model

{
    "name": "Address",
    "base": "PersistedModel",
    "idInjection": true,
    "options": {
        "validateUpsert": true
    },
    "properties": {
        "addressLineOne": {
            "type": "string",
            "required": true
        },
    },
    "validations": [],
    "relations": {    
        "city": {
            "type": "hasOne",
            "model": "city",
            "foreignKey": "cityId"
        }
    },
    "acls": [],
    "methods": {}
}

City Model

{
    "name": "City",
    "base": "PersistedModel",
    "idInjection": true,
    "options": {
        "validateUpsert": true
    },
    "properties": {
        "cityName": {
            "type": "string",
            "required": true
        }
    },
    "validations": [],
    "relations": {},
    "acls": [],
    "methods": {}
}

Solution

  • For Address model change relation from hasOne to belongsTo:

    ...
    "relations": {    
        "city": {
            "type": "belongsTo",
            "model": "City",
            "foreignKey": "cityId"
        }
    }
    ...
    

    BelongsTo relation adds foreign key to the Address model. So every address will have a cityId.

    And for City model you can add relation like so:

    "relations": {    
        "addresses": {
            "type": "hasMany",
            "model": "Address",
            "foreignKey": "cityId"
        }
    }
    

    Now you will be able to get all addresses for any city.

    P.S. I am pretty sure that when configuring relation, you need to use exact model name for model: "model": "City" or "model": "Address", like you setted it in your model description:

    {
       "name": "Address",
       "base": "PersistedModel",
       "idInjection": true,
    ...