Crecto
Search…
Crecto::Repo::Query
The Query class provides building robust composable query builder for retrieving and manipulate data.
Generally (but not necessary), its easiest to define a shortcut variable at the top level of your application.
1
Query = Crecto::Repo::Query
Copied!
The query object can be composed and manipulated before being used.
1
query = Query.new
2
query = query.where(is_admin: true) if role === "admin"
3
query = query.where(is_user: true) if role === "user"
4
Repo.all(User, query)
Copied!

Query methods

where

1
Query.where(name: "Aaliyah").where(is_admin: false)
Copied!

or_where

1
Query.where(role: "admin").or_where(role: "user")
Copied!

select

1
Query.select(["id", "name"])
Copied!

limit

1
Query.where(name: "Usher").limit(10)
Copied!

offset

1
Query.where(name: "Aretha").limit(10).offset(10)
Copied!

order_by

1
Query.order_by("created_at DESC")
Copied!

join

1
# SELECT * FROM users INNER JOIN images ON images.user_id = users.id
2
# WHERE images.file_name = ?
3
class User
4
# schema ...
5
has_many :images
6
end
7
8
class Image
9
schema "images" do
10
field :file_name
11
end
12
13
belogns_to :user
14
end
15
query = Query.join(:images).where("images.file_name = ?", "crystal.jpg")
16
Repo.all(User, query)
Copied!

distinct

1
Query.distinct("users.name")
Copied!

group_by

1
Query.where(name: "Charlize").join(:posts).group_by("users.id")
Copied!

preload

1
Query.preload(:images)
Copied!

Nested grouped queries

and

With a block:
1
query = Query.where(foo: "bar").and do |q|
2
q.where(name: "GZA").or_where(name: "RZA")
3
end
Copied!
With multiple query objects:
1
query = Query.where(foo: "bar").and(
2
Query.where(name: "GZA").or_where(name: "RZA")
3
)
Copied!
Would both produce the same query from Repo.all(User, query):
1
SELECT users.* FROM users WHERE ((users.foo='bar') AND ((users.name='GZA') OR (users.name='RZA')))
Copied!

or

With a block:
1
query = Query.where(foo: "bar").or do |q|
2
q.where(foo: "baz").where(name: "ODB")
3
end
Copied!
With multiple query objects:
1
query = Query.where(foo: "bar").or(
2
Query.where(foo: "baz").where(name: "ODB")
3
)
Copied!
Would both produce the same query from Repo.all(User, query):
1
SELECT users.* FROM users WHERE ((users.foo='bar') OR ((users.foo='baz') AND (users.name='ODB')))
Copied!
Last modified 3yr ago