Question

I am using loopback for API design and data modeling. I am using MySQL as my database. Although my API rest URL successfully returns results e.g. /states/{id}/cities. I have following model but it seems no foreign key relation is added. Following are my model definition.

"state": {
  "options": {
    "relations": {
      "cities": {
        "type": "hasMany",
        "model": "city",
        "foreignKey": "stateId"
      }
    }
  },
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "public": true,
  "dataSource": "db",
  "plural": "states"
},
"city": {
  "options": {
    "relations": {
      "state": {
        "type": "belongsTo",
        "model": "state",
        "foreignKey": "stateId"
      }
    }
  },
  "properties": {
    "name": {
      "type": "string"
    }
  },
  "public": true,
  "dataSource": "db",
  "plural": "cities"
}

and below is screenshot of city table. enter image description here

And following is State table screenshot. enter image description here

I may be doing it wrong here. Looking forward for any pointers.

Was it helpful?

Solution

It seems Loopback handles relations in models using "WHERE" query and not based on relations. Following are details.

https://github.com/strongloop/loopback-connector-mysql/issues/16

OTHER TIPS

loopback-mysql-connector DOES SUPPORT adding foreign keys to MySQL DB using automigrate and autoupdate combined with foreignKeys key in model definition filse. But people didn't aware of this feature due to their lack of documentation.

They updated document after my discussion with them. Please check again their README: https://github.com/strongloop/loopback-connector-mysql#auto-migration

Simply put, your code should be:

bin/automigrate.js

var path = require('path');

var app = require(path.resolve(__dirname, '../server/server'));
var ds = app.datasources.db;
ds.autoupdate(null, function(err) {
  if (err) throw err;
  console.log('Finished migration');
  ds.disconnect();
});

common/models/book.json

{
  "name": "Book",
  "base": "PersistedModel",
  "idInjection": true,
  "properties": {
    "name": {
      "type": "string"
    }, "isbn": {
      "type": "string"
    },
  },
  "validations": [],
  "relations": {
    "author": {
      "type": "belongsTo",
      "model": "Author",
      "foreignKey": "authorId",
      "primaryKey": "id"
    }
  },
  "acls": [],
  "methods": {},
  "foreignKeys": {
    "authorId": {
      "name": "authorId",
      "foreignKey": "authorId",
      "entityKey": "id",
      "entity": "Author"
    }
  }
}

Then run migration script to create / update DB tables (they will have foreign keys):

node bin/automigrate.js
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top