Schema
Schemaクラスの主な用途は、Modelクラスのメソッドを使用して、モデルとコレクションを検索することです。
Schemaは、多くの場合、ルートハンドラの最初の引数としてアクセスされます。
this.get('posts', schema => {
return schema.posts.where({ isAdmin: false });
});また、serverインスタンスの.schemaプロパティからも利用できます。
server.schema.users.create({ name: 'Yehuda' });下記のメソッドから返されたModelまたはCollectionを操作するには、ModelとCollectionクラスのAPIドキュメントにあるインスタンスメソッドを参照してください。
プロパティ
db: オブジェクト
Mirageのデータベースを返します。DbのドキュメントでdbのAPIを参照してください。
メソッド
all(type: 任意): 任意
データベース内のすべてのモデルを返します。
let posts = blogPosts.all();
// [post:1, post:2, ...]associationsFor(modelName: 文字列): オブジェクト
指定された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
// }各関連付けで使用可能なフィールドについては、Associationクラスのドキュメントを参照してください。
create(type: 任意, attrs: 任意): 任意
属性attrsを使用して新しいモデルインスタンスを作成し、データベースに挿入します。
let post = blogPosts.create({title: 'Lorem ipsum'});
post.title; // Lorem ipsum
post.id; // 1
post.isNew(); // falsefind(type: 任意, ids: 任意): 任意
IDでデータベース内の1つまたは複数のモデルを返します。
let post = blogPosts.find(1);
let posts = blogPosts.find([1, 3, 4]);findBy(type: 任意, attributeName: 任意): 任意
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: 任意, attributeName: 任意): 任意
attrsのキーと値のペアに一致するデータベース内の最初のモデルを返します。一致するモデルが見つからない場合は、属性を使用してレコードを作成します。
// Find the first published blog post, or create a new one.
let post = blogPosts.findOrCreateBy({ published: true });first(type: 任意): 任意
データベース内の最初のモデルを返します。
let post = blogPosts.first();注: スキーマにレコードが含まれていない場合、nullを返します。
new(type: 任意, attrs: 任意): 任意
属性attrsを使用して、保存されていない新しいモデルインスタンスを作成します。
let post = blogPosts.new({ title: 'Lorem ipsum' });
post.title; // Lorem ipsum
post.id; // null
post.isNew(); // truenone(type: 任意): 任意
type型の空のコレクションを返します。
where(type: 任意, query: 任意): 任意
queryに一致するデータベースからのモデルの配列を表すORM/コレクションを返します。
queryがオブジェクトの場合、そのキーと値のペアは、文字列比較を使用してレコードと比較されます。
queryは比較関数にすることもできます。
let posts = blogPosts.where({ published: true });
let posts = blogPosts.where(post => post.published === true);