集合
集合表示模型的数组。它们由 hasMany 关联返回,或者由 ModelClass 的查询方法之一返回。
let posts = user.blogPosts;
let posts = schema.blogPosts.all();
let posts = schema.blogPosts.find([1, 2, 4]);
let posts = schema.blogPosts.where({ published: true });
请注意,还有一个名为 PolymorphicCollection
的类,它与 Collection
相同,只是它可以包含一个异构模型数组。因此,它没有 modelName
属性。这使得序列化器和系统的其他部分能够以不同的方式与其交互。
属性
length: 整数
集合中模型的数量。
user.posts.length; // 2
modelName: 字符串
此集合表示的模型名称(用连字符分隔)。
let posts = user.blogPosts;
posts.modelName; // "blog-post"
模型名称与实际模型是分开的,因为集合可以为空。
models: 数组
此集合中模型的底层纯 JavaScript 数组。
posts.models // [ post:1, post:2, ... ]
虽然集合具有许多类似数组的方法,例如 filter
和 sort
,但如果您想使用像 map
这样的方法,或者使用 []
访问器,使用纯数组会很有用。
例如,在测试中,您可能想要断言集合中的模型。
let newPost = user.posts.models[0].title;
assert.equal(newPost, "My first post");
方法
add(model: 模型): any
将模型添加到此集合中。
posts.length; // 1
posts.add(newPost);
posts.length; // 2
destroy(): any
销毁集合中所有模型的数据库记录。
let posts = user.blogPosts;
posts.destroy(); // all posts removed from db
filter(f: 函数): 集合
返回一个新的集合,其模型根据提供的 回调函数 进行过滤。
let publishedPosts = user.posts.filter(post => post.isPublished);
includes(): 布尔值
检查集合是否包含给定的模型。
posts.includes(newPost);
通过检查集合中是否存在给定的模型名称和 ID 来实现,使其比严格的对象相等更灵活。
let post = server.create('post');
let programming = server.create('tag', { text: 'Programming' });
visit(`/posts/${post.id}`);
click('.tag-selector');
click('.tag:contains(Programming)');
post.reload();
assert.ok(post.tags.includes(programming));
mergeCollection(collection: 集合): any
通过合并另一个集合中的模型来修改集合。
user.posts.mergeCollection(newPosts);
user.posts.save();
reload(): any
重新加载集合中的每个模型。
let posts = author.blogPosts;
// ...
posts.reload(); // reloads data for each post from the db
remove(model: 模型): any
从此集合中删除一个模型。
posts.length; // 5
let firstPost = posts.models[0];
posts.remove(firstPost);
posts.save();
posts.length; // 4
save(): any
保存集合中的所有模型。
let posts = user.blogPosts;
posts.models[0].published = true;
posts.save(); // all posts saved to db
slice(begin: 整数, end: 整数): 集合
返回一个新的集合,其中包含从 begin
到 end
选择的模型子集。
let firstThreePosts = user.posts.slice(0, 3);
sort(f: 函数): 集合
返回一个新的集合,其模型根据提供的 比较函数 进行排序。
let postsByTitleAsc = user.posts.sort((a, b) => {
return b.title < a.title;
});
toString(): 字符串
集合和 ID 的简单字符串表示。
user.posts.toString(); // collection:post(post:1,post:4)
update(key: any, val: any): any
更新集合中的每个模型,并立即将所有更改持久保存到数据库。
let posts = user.blogPosts;
posts.update('published', true); // the db was updated for all posts