Search code examples
loopbackjs

correct way to define Loopback.io belongsTo relationship


I have a simple has_many-belongst_to relationship between 2 Loopback models:

{
  "name": "ApiUser",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "postgresql": {
      "table": "users"
    },
    "validateUpsert": true
  },
  "properties": {
    "id": {
      "type": "string",
      "id": true,
      "required": true,
      "defaultFn": "uuid",
      "postgresql": {
        "dataType": "uuid"
      }
    },
    "email": {
        ...

and

{
  "name": "ShopifyAccount",
  "base": "PersistedModel",
  "idInjection": true,
  "options": {
    "validateUpsert": true
  },
  "properties": {
    "api_key": {
      "type": "string",
      "required": true
    },
    "password": {
      "type": "string",
      "required": true
    }
  },
  "validations": [],
  "relations": {
    "orders": {
      "type": "hasMany",
      "model": "ShopifyOrder",
      "foreignKey": ""
    },
    "user": {
      "type": "belongsTo",
      "model": "ApiUser",
      "foreignKey": "userid"
    }
  },
  "acls": [],
  "methods": {}
}

When I run automigration, the shopifyaccount table is created, but it looks weird:

  Column       |  Type   |                          Modifiers                          

-------------------+---------+-------------------------------------------------------------

api_key | text | not null

password | text | not null

id | integer | not null default nextval('shopifyaccount_id_seq'::regclass)

userid | uuid |

apiuserid | uuid |

Indexes:

"shopifyaccount_pkey" PRIMARY KEY, btree (id)

Why did it create 2 columns named like this? Even if I try to specify that foreignkey is "userid", it will still create the apiuserid column. The insert will never update the apiuserid column but it will update the userid column. And then at join time, it will try to join on apiuserid. What am I doing wrong?


Solution

  • So... it seems that the "foreignkey" needs to be specified in both places, in ApiUser and in ShopifyAccount:

    {
      "name": "ApiUser",
      "base": "PersistedModel",
      "idInjection": true,
      "options": {
        "postgresql": {
          "table": "users"
        },
        "validateUpsert": true
      },
      "properties": {
        "id": {
          "type": "string",
          "id": true,
          "required": true,
          "defaultFn": "uuid",
          "postgresql": {
            "dataType": "uuid"
          }
        },
        "email": {
          "type": "string",
        ...
      "relations": {
        "shopifyAccounts": {
          "type": "hasOne",
          "model": "ShopifyAccount",
          "foreignKey": "userid"
        }
      },
      "acls": [],
      "methods": {}
    }