2017-04-08 74 views
0

我試圖使用商店的時區查詢商店的訂單和date_truncinserted_at如何在Ecto片段聲明中使用帶時區的date_trunc

以下工作。

shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone 'America/Los_Angeles')", o.inserted_at)) |> Repo.all 

但當我嘗試動態傳遞的時區,我得到「無法確定1個參數$的數據類型」即使我明確地使用type投的時區作爲一個字符串

shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone '?')", o.inserted_at, type(^timezone, :string))) |> Repo.all 


** (Postgrex.Error) ERROR 42P18 (indeterminate_datatype): could not determine data type of parameter $1 
[debug] QUERY ERROR source="orders" db=1.0ms 
SELECT date_trunc('day', o0."inserted_at" at time zone '$1::varchar') FROM "orders" AS o0 WHERE (o0."shop_id" = $2) ["America/Los_Angeles", "QXJnQWw2NWxhS289"] 
    (ecto) lib/ecto/adapters/sql.ex:436: Ecto.Adapters.SQL.execute_and_cache/7 
    (ecto) lib/ecto/repo/queryable.ex:130: Ecto.Repo.Queryable.execute/5 
    (ecto) lib/ecto/repo/queryable.ex:35: Ecto.Repo.Queryable.all/4 
錯誤

在這裏使用elixir 1.4.1和ecto 2.1.4。

如何獲取正確的查詢?

在此先感謝!

+1

嘗試刪除周圍的單引號'?'爲時區:'fragment(「date_trunc('day',?at time zone?)」,...)'。 – Dogbert

+0

@Dogbert它的工作!謝謝! – he9lin

回答

2

使用fragment時,您不需要在周圍?的SQL引號(既不你需要顯式類型轉換你的固定報價錯誤後):

shop |> Ecto.assoc(:orders) |> select([o], fragment("date_trunc('day', ? at time zone ?)", o.inserted_at, ^timezone)) |> Repo.all