Loopback模型定义不在数据库表中添加外键关系

时间:2014-01-02 06:05:49

标签: loopbackjs

我正在使用环回来进行API设计和数据建模。我使用MySQL作为我的数据库。虽然我的API其他网址成功返回结果,例如/states/{id}/cities。我有以下模型,但似乎没有添加外键关系。以下是我的模型定义。

"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"
}

以下是城市表的截图。 enter image description here

以下是状态表截图。 enter image description here

我可能在这里做错了。期待任何指示。

2 个答案:

答案 0 :(得分:3)

似乎Loopback使用" WHERE"处理模型中的关系。查询而不是基于关系。 以下是详细信息。

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

答案 1 :(得分:3)

export class AppComponent { title = 'app works!'; errorMessage: string; movies: Movie[]; mode = 'Observable'; constructor(private appService: AppService){} ngOnInit(){ this.getMovies(); console.log(this.movies); <--- the value is not set to this.movies yet since data is loading asynchronously } getMovies(){ this.appService.getMovies() .subscribe( (movies) => { this.movies = movies; console.log(this.movies); <--- the value will be set here properly }, (error) => { this.errorMessage = <any>error); } } } 支持使用loopback-mysql-connectorautomigrate以及模型定义过滤中的autoupdate键将外键添加到MySQL数据库。但由于缺乏文档,人们并不知道这个功能。

他们在my discussion之后更新了文档。请再次检查他们的自述文件:https://github.com/strongloop/loopback-connector-mysql#auto-migration

简单地说,您的代码应该是:

<强>仓/ automigrate.js

foreignKeys

<强>公共/模型/ book.json

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();
});

然后运行迁移脚本来创建/更新数据库表(它们将具有外键):

{
  "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"
    }
  }
}