【问题标题】:WHERE clause with Timex.Duration in Elixir / EctoElixir / Ecto 中带有 Timex.Duration 的 WHERE 子句
【发布时间】:2017-02-08 00:33:16
【问题描述】:

我对 Elixir 和 Phoenix 很陌生(又名菜鸟)。我正在通过创建 API 来学习 elixir 和 Phoenix。但是当我使用 Timex 库时,我遇到了关于模型查询的问题。我正在尝试添加;

def find_users_randomly(query, user_id, count \\ 10) do
  from a in query,
    where: a.id != ^user_id,
    where: is_nil(a.last_time_get_msg_at),
    or_where: 45 < Timex.Duration.diff(a.last_time_get_msg_at, Duration.now, :minutes),
    order_by: [desc: :last_login_at],
    select: [:id, :uuid],
    limit: ^count
end

但是 Timex.Duration.diff(a.last_time_get_msg_at, Duration.now, :minutes) 在下面给出错误。

== Compilation error on file web/models/user.ex ==
** (Ecto.Query.CompileError) `Duration.diff(a.last_time_get_msg_at(), Duration.now(), :minutes)` is not a valid query expression

我尝试使用 dynamiccast 以及基于管道的方法,但找不到解决方案。

我可以为此做些什么?你有什么建议?

包:

{:timex, "~> 3.1"}
{:phoenix_ecto, "~> 3.0"}
{:phoenix, "~> 1.2.1"}

模型示例;

defmodule Test.User do
  use Test.Web, :model
  use Timex

  alias Timex.Duration

  schema "users" do
    field :last_login_at, Ecto.DateTime, default: Ecto.DateTime
    field :last_time_get_msg_at, Ecto.DateTime

    timestamps()
  end

  def changeset(struct, params \\ %{}) do
    struct
    |> cast(params, [:last_login_at])
    |> validate_required([:last_login_at])
  end

  def find_users_randomly(query, user_id, count \\ 10) do
    from a in query,
      where: a.id != ^user_id,
      where: is_nil(a.last_time_get_msg_at),
      or_where: 45 < Duration.diff(a.last_time_get_msg_at, Duration.now, :minutes),
      order_by: [desc: :last_login_at],
      select: [:id],
      limit: ^count
  end
end

谢谢!

【问题讨论】:

  • 您不能在这样的查询中使用Timex(或任何 Elixir 函数),因为一个参数是数据库字段。您必须在 PostgreSQL(或您使用的任何数据库)中找到等效的函数。
  • 谢谢@Dogbert。我不知道。

标签: elixir phoenix-framework ecto


【解决方案1】:

在 PostgreSQL 中,您可以减去 now() 和日期并与间隔 45 minutes 进行比较:

or_where: fragment("now() - ? <= interval '45 minutes'", a.last_time_get_msg_at),

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 2011-08-02
    • 1970-01-01
    相关资源
    最近更新 更多