關聯

關聯表示您的模型之間的關係。

hasManybelongsTo 輔助函式是您實際定義關係的方式

import { Server, Model, hasMany, belongsTo }

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

檢視關係指南以了解更多關於設定關係的資訊。

每次使用輔助函式都會在伺服器的Schema 中註冊一個關聯(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()
    })
  }
})

該關聯的 modelName 將會是 user

請注意,關聯的 modelNamename 可能不同。這是因為 Mirage 支援同一類型的多個關係

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

對於這兩個關係,modelName 都是 user,但第一個關聯的 nameauthor,而第二個關聯的 namereviewer

name: 字串

關聯的名稱,來自用於定義它的屬性名稱。

例如,給定此伺服器定義

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

關聯的 name 將會是 author

Mirage 使用該名稱在模型上定義外鍵(在本例中為 comment.authorId),以及其他事情。

方法

isReflexive(): 布林值

如果關聯是自我參照的,也就是說,如果模型與自身存在關聯,則傳回一個布林值,該值為 true。

例如,給定

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

然後

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