アソシエーション

アソシエーションはモデル間の関係を表します。

hasManybelongsTo ヘルパーは、実際に関係を定義する方法です。

import { Server, Model, hasMany, belongsTo }

new Server({
  models: {
    user: Model.extend({
      comments: hasMany()
    }),
    comments: Model.extend({
      user: belongsTo()
    })
  }
})

関係の設定について詳しくは、リレーションシップガイドをご覧ください。

ヘルパーを使用するたびに、サーバーの スキーマ にアソシエーション(HasMany アソシエーションまたは BelongsTo アソシエーション)が登録されます。これらのアソシエーションには、schema.associationsFor() メソッド、または個々のモデルインスタンスの associations プロパティを使用してアクセスできます。

その後、アソシエーションをイントロスペクトして、シリアライザーで JSON レスポンスを動的に構築するなどの操作を実行できます。

プロパティ

foreignKey: 文字列

アソシエーションの外部キーに使用される名前を返します。

let server = new Server({
  models: {
    user: Model,
    post: Model.extend({
      fineAuthor: belongsTo("user"),
      comments: hasMany()
    }),
    comment: Model
  }
});

let associations = server.associationsFor('post')

associations.fineAuthor.foreignKey // fineAuthorId
associations.comments.foreignKey // commentIds

isPolymorphic: ブール値

アソシエーションがポリモーフィックである場合は true であるブール値を返します。

例えば、

new Server({
  models: {
    comment: Model.extend({
      commentable: belongsTo({ polymorphic: true })
    })
  }
})

の場合、

server.schema.associationsFor('comment').commentable.isPolymorphic // true

詳細は、ポリモーフィックアソシエーションのガイドをご覧ください。

type: 文字列

アソシエーションタイプに基づいて、文字列 "hasMany" または "belongsTo" を返します。

modelName: 文字列

関連付けられたモデルの modelName です。

例えば、次の設定の場合

new Server({
  models: {
    user: Model,
    comment: Model.extend({
      user: belongsTo()
    })
  }
})

アソシエーションの modelNameuser になります。

アソシエーションの modelNamename は異なる場合があります。これは、Mirage が同じタイプの複数の関係をサポートしているためです。

new Server({
  models: {
    user: Model,
    comment: Model.extend({
      author: belongsTo('user'),
      reviewer: belongsTo('user')
    })
  }
})

これらの関係の両方で、modelNameuser ですが、最初のアソシエーションの nameauthor で、2 番目のアソシエーションの namereviewer です。

name: 文字列

アソシエーションの名前。定義に使用されたプロパティ名から取得されます。

例えば、次のサーバー定義の場合

new Server({
  models: {
    user: Model,
    comment: Model.extend({
      author: belongsTo('user')
    })
  }
})

アソシエーションの nameauthor になります。

この名前は、Mirage がモデルの外部キー(この場合は comment.authorId)などを定義するために使用されます。

メソッド

isReflexive(): ブール値

アソシエーションが自己参照型の場合、つまりモデルが自身とのアソシエーションを持つ場合、true であるブール値を返します。

例えば、

new Server({
  models: {
    user: Model.extend({
      friends: hasMany('user')
    })
  }
})

の場合、

server.schema.associationsFor('user').friends.isReflexive // true