LoginSignup
3
2

More than 5 years have passed since last update.

Ectoで後からwhereの条件式を追加する場合の書き方

Posted at

状況

PhoenixFrameworkのmodelを書いている時に、引数があるときだけupdated_atの指定時間より新しいレコードを取得したかった。しかし、あとからwhere句を追加する方法が情報として少なかったのでメモとして残す。

環境

Elixir 1.3.0
Ecto 1.1.8

解決方法

from/2にqueryを入れた変数を直接渡す。

サンプル

仮で下記modelがあると想定する。(PhoenixFrameworkを利用した場合のmodel)

defmodule App.Post do  
  use App.Web, :model

  schema "posts" do
    field :title, :string
    field :body, :string
    field :published, :boolean
    field :deleted, :boolean
    field :published_at, :datetime

    timestamps
  end
end

引数がtrueだった場合に、from p in base_queryの箇所で元のqueryにwhere句の条件を動的に追加している。

def all(published \\ false) do
  base_query = from p in App.Post, 
               where: p.deleted == false

  query = if published do
    from p in base_query, 
    where: p.published == true
  else
    base_query
  end

  query
  |> App.Repo.all()
end

まとめ

ここまで書いた後でQiitaを見ていたらこちらにしっかりとした情報が載っていた・・・もっと色々なクエリのサンプルが見たい方は参考までに。
とある事情でEcto 2.0が利用できない環境なので、今後はEcto 2.0もキャッチアップしてEctoの理解をもっと進めたい。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2