Crecto
Search…
Database Operations

all

Returns all records of the passed type, or matching a query
1
MyRepo.all(User)
2
3
# with a query
4
query = Crecto::Repo::Query.where(name: "Keanu")
5
MyRepo.all(User, query)
6
7
# preload associations
8
users = MyRepo.all(User, preload: [:image])
9
users.first.images # already loaded, no need to query
Copied!

get

Returns a single matching record, or nil if the record doesn't exist
1
user = MyRepo.get(User, 1)
2
user.class # User | Nil
Copied!

get!

Returns a single record by primary key, or raises an exception if there is no matching record
1
user = MyRepo.get!(User, 1) # raises Crecto::NoResults if no record exists
2
user.class # User
Copied!

get_by

Returns a single record matching the values passed, or nil if the record doesn't exist
1
user = MyRepo.get_by(User, first_name: "Dekimbe")
2
user.class # User | Nil
Copied!

get_by!

Returns a single record matching the values passed, or raises an exception if there is no matching record
1
user = MyRepo.get_by!(User, first_name: "") # raises Crecto::NoResults if no record exists
2
user.class # User
Copied!

insert

Inserts the new data model into the database, returns a changeset
1
user = User.new
2
user.name = "Tupac"
3
changeset = MyRepo.insert(user)
Copied!

update

Updates an existing data model in the database, returns a changeset
1
user = MyRepo.get!(User, 1)
2
user.name = "Madonna"
3
changeset = MyRepo.update(user)
Copied!

update_all

Updates all records of type, or matching a query if one is passed as an argument
1
MyRepo.update_all(User, {name: "Cher"})
2
3
# with query
4
query = Crecto::Repo::Query.where(name: "Adele")
5
MyRepo.update_all(User, query, {name: "Shakira"})
Copied!

delete

Deletes a single record from the database, returns a changeset
1
user = MyRepo.get!(User, 1)
2
changeset = MyRepo.delete(user)
Copied!

delete_all

Deletes all records of type, or matching a query if one is passed as an argument
1
MyRepo.delete_all(User)
2
3
# with a query
4
query = Crecto::Repo::Query.where(name: "Rihanna")
5
MyRepo.delete_all(User, query)
Copied!

aggregate

Returns the result of the passed aggregation function: :avg, :count, :max, :min, or :sum
1
MyRepo.aggregate(User, :count, :id)
2
MyRepo.aggregate(User, :avg, :age)
3
MyRepo.aggregate(User, :max, :age)
4
MyRepo.aggregate(User, :min, :age)
5
MyRepo.aggregate(User, :sum, :age)
6
7
# with a query
8
query = Crecto::Repo::Query.where(name: "Barak")
9
MyRepo.aggregate(User, :count, :id, query)
Copied!

get_association

  • get_association
  • get_association!
  • query