Repo.get(User, id) #nil or %User{}Repo.get!(User, id) #error or %UserMyRepo.get_by(Post, title: "My post") #error if not one resultRepo.all(User)Repo.all(from u inUser, select: u.email, where: u.age == ^age) #[...]Repo.one(from u inUser, where: ilike(u.email,"%1%"), select: count(u.id)) # of users with 1 in their emailRepo.one(from ea inEventAnalytics, where: ea.email =="j@g"and ea.type =="RSVP") #will error if > one response, nil if none
Supports literal Integers, Floats, Bools, Binary(<<1, 2 >>), Strings, and arrays, other external variables must be pinned^. Using with Schema(User instead of "users") lets it know what type to cast to and automatically retrieves all fields
query = from u inUser, where: u.age == ^age and u.height > ^(height_ft *3.28), order_by: u.city, preload: [:company]#Can explicitly cast typequery = from u in"users", where: u.age >type(^age, :integer), select: u.name#List of map from id to emailquery = from u inUser, select: %{u.id => u.email}, where: notis_nil(u.birthday) #Complex child query stuff idkchild_query = from c inComment, where: parent_as(:posts).id == c.post_idquery = from p inPost, as: :posts, join: c insubquery(child_query)Repo.all(query)Repo.one(query) #will error if >1 response
importEcto.Queryuid ="34547f91-ffaa-4f03-8a0f-e63daaeced0b"ReactPhoenix.Repo.all(from m inReactPhoenix.Events.Meeting, where: m.user1_id == ^uid) # use pin to use external var
Join
:inner_join, :left_join, :right_join, :cross_join, :full_join, :inner_lateral_join or :left_lateral_join. :join is equivalent to :inner_join(match both returned)
counts_and_events = from ea insubquery(count_types), join: e inEvent, on: ea.event_id == e.id, where: e.user_id == ^user_id, order_by: [desc: e.start_time],# order_by: e.start_time would be asc select: %{ id: ea.event_id, title: e.title, start_time: e.start_time, }
Repo.all( from q inQuestion, where: q.subevent_id == ^subevent_id, preload: [:user], left_join: qu inQuestionUpvote, on: qu.question_id == q.id, group_by: [q.id], select: %{question: q, upvotes: count(qu.id)})
Preload
Can be used very similarly to a join, and keeps proper select and structure
defget_event!(id) doRepo.get!(Event, id)|>Repo.preload(:subevents)endRepo.all(from q inQuestion, where: q.subevent_id == ^subevent_id, preload: [user])# seperating ra_query first gets all the reqs then fills in the association(if joined with where it wouldn't return reqs without ra with the right email)ra_query = from ra inRegistrationAnswer, where: ra.email == ^emailRepo.all(from req inRegistrationEventQuestion, where: req.event_id == ^event_id, preload: [registration_answers: ^ra_query], select: req)