【问题标题】:Building where clauses?构建where子句?
【发布时间】:2018-02-09 11:11:12
【问题描述】:

我希望能够为查询构建 where 子句。我想输入一个 where 条件数组并使用 korma 构建查询,如下所示:

(defn ^:private fetch-by
  "Append conditions to the query."
  [query ^clojure.lang.PersistentVector conditions]

  (for [condition conditions]
    (if (instance? clojure.lang.PersistentArrayMap condition)
      (korma/where query condition) query)))

但是,这里的 for 循环会复制查询对象。是否可以合并这些对象或您可以推荐的其他方法来实现所需的输出?

【问题讨论】:

  • 不是 korma 方面的专家,但似乎 (->> conditions (filter map?) (apply merge) (korma/where query)) 应该在这里工作

标签: clojure korma sqlkorma


【解决方案1】:

conditions合并到一个查询映射可以用reduce完成:

(defn ^:private fetch-by
  "Append conditions to the query."
  [query conditions]
  (->> (filter map? conditions)
       (reduce (fn [query condition]
                 (korma/where query condition))
               query)))

这里您的初始reduce 状态是您传入的任何query,归约函数(和korma/where)负责将每个条件合并到查询映射中。

(-> (korma/select* :my-table)
    (fetch-by [{:active true}
               {:deleted false}])
    (korma/as-sql))
 => "SELECT \"my-table\".* FROM \"my-table\" WHERE (\"my-table\".\"active\" = ?) AND (\"my-table\".\"deleted\" = ?)"

然而,这与仅将具有多个条目的单个映射传递给 korma/where 并没有什么不同:

(-> (korma/select* :my-table)
    (korma/where {:active true
                  :deleted false})
    (korma/as-sql))

只要条件的键是唯一的,我会建议这样做。

【讨论】:

  • 感谢您提供如此详细的答案!
猜你喜欢
  • 2015-06-22
  • 2011-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-28
  • 2017-08-24
相关资源
最近更新 更多