关联

关联代表模型之间的关系。

使用 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: String

返回关联的外键的名称。

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: Boolean

返回一个布尔值,如果关联是多态的,则为 true。

例如,给定

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

那么

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

查看 有关多态关联的指南,了解有关该主题的更多信息。

type: String

根据关联类型,返回字符串 "hasMany""belongsTo"

modelName: String

关联模型的 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: String

关联的名称,来自用于定义它的属性名称。

例如,给定以下服务器定义

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

关联的 name 将是 author

Mirage 使用该名称在模型上定义外键(在本例中为 comment.authorId),以及其他功能。

方法

isReflexive(): Boolean

返回一个布尔值,如果关联是自引用的,即模型与自身具有关联,则为 true。

例如,给定

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

那么

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