Clear ORM
  • Welcome to Clear
  • Introduction
    • Setup
  • Model
    • Defining your model
      • Describing your columns
      • Primary Keys
      • Converters
    • Associations
      • belongs_to
      • has_many
      • has_many through
      • has_one
    • Lifecycle
      • Persistence
      • Validations
      • Triggers
    • Batchs operations
      • Bulk update
      • Bulk insert & delete
    • Transactions & Save Points
      • Transaction & Savepoints
      • Connection pool
    • Locks
  • Querying
    • The collection object
      • Filter the query
        • Filter the query – The Expression Engine
        • Find, First, Last, Offset, Limit
        • Aggregation
        • Ordering & Group by
      • Fetching the query
        • Each and Fetch
        • Cursored fetching
        • Model extra attributes
      • Joins
      • Eager Loading
      • Window and CTE
      • Scopes
    • Writing low-level SQL
      • Select Clause
      • Insert Clause
      • Delete Clause
  • Migrations
    • Manage migrations
    • Call migration script
    • Migration CLI
  • Additional and advanced features
    • JSONB
    • Symbol vs String
    • Enums
    • BCrypt
    • Full Text Search
    • Handling multi-connection
  • Other resources
    • API Documentation
    • Inline documentation
    • Github repository
    • Credits
    • Benchmark
Powered by GitBook
On this page
  • Collection and SELECT query
  • Mutability
  1. Querying

The collection object

Each model offers an object called ModelName::Collection. This Collection object offers a way to query the database and perform operations on large groups of model.

To instantiate a new Collection, you can simply call the method query over the model class:

users = User.query

Collection and SELECT query

When instantiated, the collection is Crystal implementation of a SELECT query:

-- Users.query ==
SELECT * FROM users

Therefore, calling to_a over the Collection will fetch all the models from the database to your crystal code:

array_of_users = User.query.to_a

Collection will really perform SQL request only on resolution time, when calling each or to_a for example.

Mutability

Collection are mutable objects, and many of the methods will change the state of the collection:

query = User.query # SELECT * FROM users;
query.select("id") # SELECT id FROM users;
query.select("id") # SELECT id, id FROM users;

Therefore, you may want to use Collection#dup to duplicate the current state of the collection:

query = User.query # SELECT * FROM users;
query.select("id") # SELECT id FROM users;

query2 = collection.dup # SELECT id FROM users;
PreviousLocksNextFilter the query

Last updated 5 years ago

Collection can be filtered and refined to query exactly what you want. Actually, they are refined version of SQL::SelectBuilder object .

described in Low-level SQL chapter