Saw Thinkar Nay Htoo
Saw Thinkar Nay Htoo

Reputation: 396

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

Upvotes: 6

Views: 6302

Answers (2)

Dennis
Dennis

Reputation: 59607

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)

Upvotes: 14

Badu
Badu

Reputation: 1082

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

Upvotes: 3

Related Questions