模式
Schema
类的主要用途是使用它通过 Model
类的 方法找到模型和集合。
Schema
通常通过路由处理程序的第一个参数访问。
this.get('posts', schema => {
return schema.posts.where({ isAdmin: false });
});
它也可以从 server
实例的 .schema
属性访问。
server.schema.users.create({ name: 'Yehuda' });
要使用从以下方法之一返回的模型或集合,请参考 API 文档中 Model
和 Collection
类的实例方法。
属性
db: Object
返回 Mirage 的数据库。有关数据库 API,请参阅 Db
文档。
方法
all(type: any): any
返回数据库中的所有模型。
let posts = blogPosts.all();
// [post:1, post:2, ...]
associationsFor(modelName: String): Object
返回一个对象,其中包含为给定 modelName 的模型注册的关联。
例如,给定以下配置
import { Server, Model, hasMany, belongsTo } from 'miragejs'
let server = new Server({
models: {
user: Model,
article: Model.extend({
fineAuthor: belongsTo("user"),
comments: hasMany()
}),
comment: Model
}
})
以下每个都将返回空对象
server.schema.associationsFor('user')
// {}
server.schema.associationsFor('comment')
// {}
但 article
的关联将返回
server.schema.associationsFor('article')
// {
// fineAuthor: BelongsToAssociation,
// comments: HasManyAssociation
// }
查看有关关联类的文档,了解每个关联可用的字段。
create(type: any, attrs: any): any
使用属性 attrs 创建一个新的模型实例,并将其插入数据库。
let post = blogPosts.create({title: 'Lorem ipsum'});
post.title; // Lorem ipsum
post.id; // 1
post.isNew(); // false
find(type: any, ids: any): any
通过 ID 返回数据库中的一个或多个模型。
let post = blogPosts.find(1);
let posts = blogPosts.find([1, 3, 4]);
findBy(type: any, attributeName: any): any
返回数据库中第一个匹配 attrs
中的键值对的模型。请注意,使用的是字符串比较。
let post = blogPosts.findBy({ published: true });
let post = blogPosts.findBy({ authorId: 1, published: false });
let post = blogPosts.findBy({ author: janeSmith, featured: true });
如果模式没有匹配的记录,这将返回 null
。
findOrCreateBy(type: any, attributeName: any): any
返回数据库中第一个匹配 attrs
中的键值对的模型,或者如果找不到,则使用这些属性创建一个记录。
// Find the first published blog post, or create a new one.
let post = blogPosts.findOrCreateBy({ published: true });
first(type: any): any
返回数据库中的第一个模型。
let post = blogPosts.first();
注意:如果模式不包含任何记录,这将返回 null
。
new(type: any, attrs: any): any
使用属性 attrs 创建一个新的未保存的模型实例。
let post = blogPosts.new({ title: 'Lorem ipsum' });
post.title; // Lorem ipsum
post.id; // null
post.isNew(); // true
none(type: any): any
返回类型为 type
的空集合。
where(type: any, query: any): any
返回一个 ORM/Collection,它表示数据库中匹配 query
的模型数组。
如果 query
是一个对象,则使用字符串比较将其键值对与记录进行比较。
query
也可以是一个比较函数。
let posts = blogPosts.where({ published: true });
let posts = blogPosts.where(post => post.published === true);