Search code examples
phoenix-frameworkecto

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}


Solution

  • 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)