Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ecto.Repo to check if id exists in the database, Phoenix framework

  • How do I check if an id exists in the database?

    def get_user!(id), do: Repo.get!(User, id)
    
  • get_user!(id) can be used to get the user, is there a way to check if id exists?

  • I want something like below which would return true.

    MyApp.Accounts.get_user!(user_id) == %MyApp.Accounts.User{id: user_id}

like image 515
Saw Thinkar Nay Htoo Avatar asked Jun 05 '18 10:06

Saw Thinkar Nay Htoo


People also ask

What is Ecto in Phoenix?

Ecto is a persistence framework for Elixir. That is a fancy way of saying that we use Ecto to talk to a SQL database. This chapter will introduce you to the very basics of Ecto in the Phoenix context. This means that whenever available, we use functions that were created by Phoenix generators.

What is an ecto repository?

0.4 Ecto. Repo behaviour. 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.

What databases does ecto support?

Ecto is commonly used to interact with databases, such as PostgreSQL and MySQL via Ecto. Adapters. SQL (source code). Ecto is also commonly used to map data from any source into Elixir structs, whether they are backed by a database or not.


2 Answers

Ecto v3 supports this with Ecto.Repo.exists?/2

import Ecto.Query, only: [from: 2]

Repo.exists?(from u in User, where: u.id == ^user_id)
like image 155
Dennis Avatar answered Oct 11 '22 14:10

Dennis


Repo.get! throws an error if no record is found. You might want to use Repo.get instead like

Repo.get(User, user_id) != nil

You can also define a function to check if a give user id exists

def user_exist_by_id(user_id)do
    #select just id to reduce payload
    query = (from u in User, where: u.id == ^user_id, select: %{id: u.id})
    found = Repo.one(query)
    #if not result, found will be nil
    found != nil
end
like image 38
Badu Avatar answered Oct 11 '22 13:10

Badu