Ecto Repo.get_by with multple 'or' clauses
Asked Answered
G

1

6

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) 
Grownup answered 31/8, 2018 at 11:29 Comment(0)
F
11

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.

Fertile answered 31/8, 2018 at 11:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.