Search code examples
mysqlnode.jsloopbackjsmysql-connectorrelationships

How to Choose Which Field a Foreign Key References in LoopbackJS


I would like to know how to choose a field which a foreign key references. I can't find it in the docs.

For example, if I have a Product table and a ProductTag table. A Product hasMany ProductTags. Then my ProductTag table will have a foreign key to the Product table via:

{ // Product
  ...
  "relations": {
    "productTags": {
      "type": "hasMany",
      "model": "ProductTag",
      "foreignKey": ""
    }
  }
}

The fields of my Product table are id - i want to set this as id, sku - unique, price, etc...

Then the relationship will create a foreign key referencing Product.id. How do I reference it to Product.sku instead?

Thank you!


Solution

  • From the documentation

      "relations": {
        "orders": {
          "type": "hasMany",
          "model": "Order",
          "foreignKey": "customerId",
          "primaryKey": "id" // optional
        },
    

    The target model, Order, has a property, customerId, as the foreign key to reference the declaring model (Customer) primary key id.