Schema

Schema 類別的主要用途是透過 Model 類別方法來尋找模型和集合。

Schema 最常透過路由處理程式的第一個參數存取

this.get('posts', schema => {
  return schema.posts.where({ isAdmin: false });
});

它也可以從 server 實例的 .schema 屬性中取得

server.schema.users.create({ name: 'Yehuda' });

若要使用從下列方法之一傳回的模型或集合,請參閱 ModelCollection 類別的 API 文件中的實例方法。

屬性

db: 物件

傳回 Mirage 的資料庫。請參閱 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
// }

請查看關聯類別的文件,以了解每個關聯有哪些可用的欄位。

create(type: 任何, attrs: 任何): 任何

使用屬性 attrs 建立新的模型實例,並將其插入資料庫。

let post = blogPosts.create({title: 'Lorem ipsum'});
post.title;   // Lorem ipsum
post.id;      // 1
post.isNew(); // false

find(type: 任何, ids: 任何): 任何

依 ID 傳回資料庫中的一個或多個模型。

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 });

如果 schema 沒有任何符合的記錄,則會傳回 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();

注意:如果 schema 不包含任何記錄,則會傳回 null

new(type: 任何, attrs: 任何): 任何

使用屬性 attrs 建立新的未儲存模型實例。

let post = blogPosts.new({ title: 'Lorem ipsum' });
post.title;   // Lorem ipsum
post.id;      // null
post.isNew(); // true

none(type: 任何): 任何

傳回 type 類型的空集合。

where(type: 任何, query: 任何): 任何

傳回 ORM/集合,其表示資料庫中符合 query 的模型陣列。

如果 query 是物件,則會使用字串比較來比較其鍵值對與記錄。

query 也可以是比較函式。

let posts = blogPosts.where({ published: true });
let posts = blogPosts.where(post => post.published === true);