How to Write Queries with Schemas
Learn how to write queries with schemas.
When we looked at queries in the last chapter, we deliberately chose to write them without schemas. This is still a good choice in certain circumstances, but schemas provide some helpful shortcuts and we promised that we’d revisit them later. Now’s the time. In this section, we’ll start writing queries that work with schemas and consider when it’s best not to.
Convert a schema-less query
Let’s look at a query we ran in the last chapter:
artist_id = "1"q = from "artists", where: [id: type(^artist_id, :integer)],select: [:name]Repo.all(q)
As you may recall, artist_id
is initialized as a string, but the id
column in the artists
table is an integer. Thus, we have to convert the value ourselves using the type function.
In addition, we have to use the select
option to specify what columns we want to be returned to us. This is not so bad since ...