Select

You can select a subset of columns to be fetched from the database:

  1. class UserRepository < Hanami::Repository
  2. def all_with_name
  3. users.select(:id, :name)
  4. end
  5. end

Raw SQL

You can perform queries with raw SQL:

  1. class UserRepository < Hanami::Repository
  2. def all_by_sql
  3. users.read("SELECT * FROM users")
  4. end
  5. end

Sort

You can sort records using #order:

  1. class UserRepository < Hanami::Repository
  2. def from_first_to_last
  3. users.order { created_at.asc }
  4. end
  5. def from_last_to_first
  6. users.order { created_at.desc }
  7. end
  8. def alphabetical
  9. users.order { name.asc }
  10. end
  11. def alphabetical_reverse
  12. users.order { name.desc }
  13. end
  14. def sort_via_other_relation
  15. users.order(books[:title].qualified.asc)
  16. end
  17. end

Limit

You can use #limit to limit the number of records fetched from the database:

  1. class UserRepository < Hanami::Repository
  2. def last_created(number)
  3. users.order { created_at.desc }.limit(number)
  4. end
  5. end

SQL Functions

You can use any SQL functions like ILIKE, IN, NOT, LENGTH, etc.. These functions are available as Ruby methods inside the #where block:

  1. class UserRepository < Hanami::Repository
  2. def by_name(name)
  3. users.where { name.ilike("%?%", name) }
  4. end
  5. def by_id_in(input)
  6. users.where { id.in(input) }
  7. end
  8. def by_id_in_range(range)
  9. users.where { id.in(range) }
  10. end
  11. def by_id_min_max(min, max)
  12. users.where { id > min || id < max }
  13. end
  14. def by_not_id(input)
  15. users.where { id.not(input) }
  16. end
  17. def by_id_not_in_range(range)
  18. users.where { id.not(1..100) }
  19. end
  20. def by_name_length(input)
  21. users.where { length(:name) > input }
  22. end
  23. end

Joins

You can join several relations:

  1. class BookRepository < Hanami::Repository
  2. associations do
  3. has_many :comments
  4. end
  5. def commented_within(date_range)
  6. books
  7. .join(comments)
  8. .where(comments[:created_at].qualified => date_range)
  9. .as(Book)
  10. end
  11. end

For a given relation named :books, the used foreign key in :comments is :book_id. That is the singular name of the relation with _id appended to it.

In case your database schema doesn’t follow this convention above, you can specify an explicit foreign key:

  1. class BookRepository < Hanami::Repository
  2. associations do
  3. has_many :comments
  4. end
  5. def commented_within(date_range)
  6. books
  7. .join(comments, id: :book_fk_id)
  8. .where(comments[:created_at].qualified => date_range)
  9. .as(Book).to_a
  10. end
  11. end

You can also use #inner_join method.

Group by

  1. class UserRepository < Hanami::Repository
  2. associations do
  3. has_many :books
  4. end
  5. def users_group_by_id
  6. users.
  7. left_join(:books).
  8. group(:id)
  9. end
  10. end