Skip to content

Instantly share code, notes, and snippets.

@mike-zipit
Last active May 25, 2018 18:20
Show Gist options
  • Save mike-zipit/20a3f24435b5891ef83ee534529ac4b2 to your computer and use it in GitHub Desktop.
Save mike-zipit/20a3f24435b5891ef83ee534529ac4b2 to your computer and use it in GitHub Desktop.
Loopback 3.x MySQL Foreign Key notes

Examples below assume a Customer that hasMany Clients, and a Client belongsTo a Customer. And, a Customer hasOne Administrator (for example purposes)

belongsTo

belongsTo must include exact foreignKey entry of column name of this table that links to the parent table

  • Client "relations" section:
    "type": "belongsTo",
    "model": "Customer",                     
    "foreignKey": customerId"
  • Note the model/foreignKey same base

hasMany

hasMany must include a foreignKey entry that is the column name of the destination table that references the this table.

  • Customer "relations" section:
    "type": "hasMany",
    "model": "Client",
    "foreignKey": "customerId"
  • Note the model/foreignKey different base

hasOne

hasOne must not include the name in the foreign key. Enter it as "foreignKey": ""

  • Customer "relations" section:
    "type": "hasOne",
    "model": "Administrator",
    "foreignKey": ""

Foreign Keys in the model.json file (MySQL specific)

Designate foreign keys as follows:

  "foreignKeys": {
    "customer": {
      "name": "fk_Client_customerId",
      "foreignKey": "customerId",
      "entityKey": "id",
      "entity": "Customer"
    }
  • Notes:
    • My naming convention fk_{Model}_{Field} to be unique
    • The "name" must be unique across ALL models, otherwise you get a cryptic error message about being unable to drop a temporary table
    • You must call automigrate and then autoupdate (i.e. 2 passes) to force loopback-connector-mysql to create the foreign key indices
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment