Collections

Introduction

Instances of the @ostro/database/eloquent/collection class, including results received via the get method or accessible via a relationship, are returned by all Eloquent methods that return more than one model result. Eloquent collection objects naturally inherit hundreds of methods for interacting with the underlying array of Eloquent models since they extend OstroJS basic collection. To understand more about these practical ways, be sure to study the OstroJS collection documentation!

Every collection also functions as an iterator, enabling you to cycle through them just like regular NodeJS arrays:

const User = require('~/app/models/user');
let users = await User.where('active', 1).get();

for (let user of users) {
   console.log(user.name);
}

Collections, on the other hand, are far more powerful than arrays and enable a range of map/reduce operations that may be linked using a user-friendly interface. For instance, we might exclude all inactive models before collecting the first name of each user that is still active:

let users =  await User.all();
let names = users.reject(function (user) {
   return user.active === false;
}).map(function (user) {
   return user.name;
});

The collapse, flatten, flip, keys, pluck, and zip methods return a base collection instance as opposed to the majority of Eloquent collection methods that return a new instance of an Eloquent collection. In the same way, a collection returned by a map operation that doesn't include any Eloquent models will be changed into a basic collection instance.