Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto Repo.get_by with multple 'or' clauses

Tags:

elixir

ecto

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) 
like image 895
Danny Ellis Jr. Avatar asked Aug 31 '18 11:08

Danny Ellis Jr.


People also ask

How does ecto Repo work?

Ecto.Repo behaviour. A repository maps to an underlying data store, controlled by the adapter. For example, Ecto ships with a Postgres adapter that stores data into a PostgreSQL database. When used, the repository expects the :otp_app as option. The :otp_app should point to an OTP application that has the repository configuration.

What is a repository in Ecto?

Defines a repository. A repository maps to an underlying data store, controlled by the adapter. For example, Ecto ships with a Postgres adapter that stores data into a PostgreSQL database. When used, the repository expects the :otp_app and :adapter as option.

How to use PostgreSQL with ecto?

For example, Ecto ships with a Postgres adapter that stores data into a PostgreSQL database. When used, the repository expects the :otp_app and :adapter as option. The :otp_app should point to an OTP application that has the repository configuration.

What is an ecto query?

Queries are used to retrieve and manipulate data from a repository (see Ecto.Repo ). Ecto queries come in two flavors: keyword-based and macro-based.


1 Answers

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.

like image 200
Dogbert Avatar answered Oct 10 '22 18:10

Dogbert