Danny Ellis Jr.
Danny Ellis Jr.

Reputation: 1706

Ecto Repo.get_by with multple 'or' clauses

I am attempting use Ecto Repo.get_by with multiple clauses, and I'm having trouble finding syntax examples. I need to query where either or 2 fields in the DB match, so an 'or' condition between the clauses. I can't figure out if this is even possible.

Repo.get_by(User, [username: username, email: username], prefix: :accounts) 

Upvotes: 6

Views: 5226

Answers (1)

Dogbert
Dogbert

Reputation: 222398

Repo.get_by doesn't allow ORing the clauses. You'll need to write a full query using from, or a combination of where and or_where, and then pipe to Repo.one:

from(u in User, where: u.username == ^username or u.email == ^username)
|> Repo.one
User
|> where(username: ^username)
|> or_where(email: ^username)
|> Repo.one

To add the prefix to this query, you can do this.

Upvotes: 11

Related Questions