module Marten::DB::Model::Querying

Direct including types

Defined in:

marten/db/model/querying.cr

Macro Summary

Macro Detail

macro default_scope #

Allows to define a default scope for the model query set.

The default scope is a set of filters that will be applied to all the queries performed on the model. For example:

class Post < Marten::Model
  field :id, :big_int, primary_key: true, auto: true
  field :title, :string, max_size: 255
  field :is_published, :bool, default: false

  default_scope { filter(is_published: true) }
end

[View source]
macro scope(name, &block) #

Allows to define a custom scope for the model query set.

Custom scopes allow to define reusable query sets that can be used to filter records in a specific way. For example:

class Post < Marten::Model
  field :id, :big_int, primary_key: true, auto: true
  field :title, :string, max_size: 255
  field :is_published, :bool, default: false

  scope :published { filter(is_published: true) }
  scope :unpublished { filter(is_published: false) }
end

published_posts = Post.published
unpublished_posts = Post.unpublished

query_set = Post.all
published_posts = query_set.published

Custom scopes can also receive arguments. To do so, required arguments must be defined within the scope block. For example:

class Post < Marten::Model
  field :id, :big_int, primary_key: true, auto: true
  field :title, :string, max_size: 255
  field :author, :many_to_one, to: Author

  scope :by_author_id { |author_id| filter(author_id: author_id) }
end

posts_by_author = Post.by_author_id(123)

[View source]