问题描述
- 某用户想要查找由 2020 年 10 月之前加入的用户创建的所有帖子
- 某用户想要查找由 2020 年 10 月之后加入的用户创建的所有帖子
- 某用户想要查找由 2020 年 10 月 5 日加入的用户创建的所有帖子
通常我需要像这样编写这个查询的各种版本:
def before_date(query,date) do
query
|> where([posts,users],users.inserted_at < ^date))
end
def after_date(query,users.inserted_at > ^date))
end
def on_date(query,users.inserted_at == ^date))
end
然后要过滤帖子日期本身,我需要重新编写这些查询并使用 posts.inserted_at 代替。
因此,我正在寻找一种方法来动态比较内部项目和 Ecto 查询。
我发现了这个问题: Create Ecto query with dynamic operators
但它没有编译,因为它抱怨查询无效:
== Compilation error in file lib/mmsapi/liquid/search/filters.ex ==
** (CompileError) lib/mmsapi/liquid/search/filters.ex:338: invalid call operator(field(o,^field_name),^value)
expanding macro: Liquid.Search.Filters.custom_where/4
所以稍微修改一下,通过用实际操作符替换变量操作符来实现:
defmacrop custom_where(t,f,v,:==) do
{:==,[context: Elixir,import: Kernel],[
{:field,[],[t,{:^,[f]}]},[v]}
]}
end
def compare_field(query,field_name,value,operator) do
query
|> where([o],^custom_where(o,operator))
end
但是我得到这个错误:
== Compilation error in file lib/mmsapi/liquid/search/filters.ex ==
** (CompileError) lib/mmsapi/liquid/search/filters.ex:327: cannot use ^field_name outside of match clauses
这是我想要实现的代码:
field_name = :inserted_at
value = DateTime.utc_Now()
operator = :==
query
|> where([posts,custom_where(users,operator))
任何帮助将不胜感激,并提前感谢您!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)