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

2

6
  • 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}

Township answered 5/6, 2018 at 10:4 Comment(0)
S
14

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)
Sweeps answered 7/2, 2019 at 16:42 Comment(1)
Super useful! Thanks.Evenings
B
3

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
Burette answered 10/6, 2018 at 11:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.