loopbackでモデルのrelationを定義する
loopbackでモデルを作成するときslcコマンドで作成できるのだけど、 モデル間のリレーションを同様にscafoldするやり方のメモです。
ここでは1対多となるモデルのリレーションの定義をslcコマンドで行ってみます。 例としてRempUserというユーザが複数のプレイリストを持つケースを想定します。
ユーザのモデルは既に作成されているものとして、プレイリストを管理するモデルを復習がてら作成します。
$ slc loopback:model ? Enter the model name: Playlist ? Select the data-source to attach Playlist to: db (mongodb) ? Select model's base class: PersistedModel ? Expose Playlist via the REST API? Yes ? Custom plural form (used to build REST URL): Let's add some Playlist properties now. Enter an empty property name when done. ? Property name: title invoke loopback:property ? Property type: string ? Required? Yes Let's add another Playlist property. Enter an empty property name when done. ? Property name: published invoke loopback:property ? Property type: boolean ? Required? Yes Let's add another Playlist property. Enter an empty property name when done. ? Property name:
次に先ほど作成したプレイリストのモデルとユーザモデルの間のリレーションを定義します。
これもscafoldできて slc loopback:relation
というコマンドで実現できます。
$ slc loopback:relation ? Select the model to create the relationship from: RempUser ? Relation type: has many ? Choose a model to create a relationship with: playlist ? Enter the property name for the relation: playlists ? Optionally enter a custom foreign key: ? Require a through model? No $ slc loopback:relation ? Select the model to create the relationship from: playlist ? Relation type: belongs to ? Choose a model to create a relationship with: RempUser ? Enter the property name for the relation: RempUser ? Optionally enter a custom foreign key:
このコマンドで具体的に行われるのは common/models/*.json
で保管されている各モデルの定義が記載されているJSON中 relations
という
要素に定義が追加されます。
実際に該当のJSONファイルを見てみると、例えばユーザモデルであれば、
{ "name": "RempUser", "base": "User", "idInjection": true, "options": { "validateUpsert": true }, "properties": {}, "validations": [], "relations": { "playlists": { "type": "hasMany", "model": "Playlist", "foreignKey": "" } }, "acls": [], "methods": [] }
といった具合にプレイリストモデルとのリレーションの定義が追加されていることがわかります。
また、loopbackの特徴であるモデル定義がそのままAPIとして反映されているので、loopbackのAPI Explorerを介して該当モデルの エントリポイントを確認してみると、
ただ、今回の例の場合、新しく作成されている /RempUsers/:id/playlists
といったエントリポイントにアクセスをしても HTTP/1.1 401 Unauthorized となってしまいます。
これは、loopbackで設けられているAPIに対するアクセスコントロールによるものなのですが、この辺りを解決するやり方はまた次回。
参考
StrongLoop | Defining and Mapping Data Relations with LoopBack Connected Models