Raw SQL

You can perform queries with raw SQL:

  1. def all_by_sql
  2. users.read("SELECT * FROM users")
  3. end
  4. end

You can sort records using #order:

Limit

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

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

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. end
  10. end

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

You can also use #inner_join method.

  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