【发布时间】:2016-01-27 14:31:05
【问题描述】:
所以我有一个 cmets 的数据库表,并且我学会了如何使用 WITH RECURSIVE 以树的形式返回一个主题的所有 cmets。但是,因为是 SQL,所以只是作为列表返回。
当我执行查询时,这些是我返回的结果(级别不是表上的列,它是由查询在收集结果时计算的):
[
{
:id "1"
:parent_id nil,
:content "This is another top-level comment",
:level "1",
:rating 0,
}
{
:id "2"
:parent_id "1",
:content "What a comment!",
:level "1 -> 2",
:rating 0,
}
{
:id "4"
:parent_id "2",
:content "Trying to see how trees work",
:level "1 -> 2 -> 4",
:rating 0,
}
{
:id "3"
:parent_id "2",
:content "No idea how this will turn out",
:level "1 -> 2 -> 3",
:rating 0,
}
{
:id "5"
:parent_id nil,
:content "This is a top-level comment",
:level "5",
:rating 0,
}
{
:id "9"
:parent_id "5",
:content "This is yet another testing comment",
:level "5 -> 9",
:rating 0,
}
{
:id "8"
:parent_id "7",
:content "It sure is!",
:level "5 -> 7 -> 8",
:rating 0,
}
{
:id "7"
:parent_id "5",
:content "This!",
:level "5 -> 7",
:rating 0,
}
{
:id "6"
:parent_id "5",
:content "Hey look at me",
:level "5 -> 6",
:rating 0,
}
]
我想弄清楚的是如何转动多棵树,所以我最终会得到这样的结果:
1 'This is another top-level comment'
↳ 2 'What a comment!'
↳ 4 'Trying to see how trees work'
↳ 3 'No idea how this will turn out'
5 'This is a top-level comment'
↳ 9 'This is yet another testing comment'
↳ 7 'This!'
↳ 8 'It sure is!'
↳ 6 'Hey look at me'
使用这个函数只能得到第一棵树(根节点为 1 的树):
(defn make-tree
([coll] (let [root (first (remove :parent coll))]
{:node root :children (make-tree root coll)}))
([root coll]
(for [x coll :when (= (:parent_id x) (:id root))]
{:node x :children (make-tree x coll)})))
关于如何修改该函数或更改我传入的内容以得到多棵树的任何想法或提示?
【问题讨论】:
-
你有一片森林,而不是一棵树。您可以有一个特殊节点,所有具有
nil父级的 cmets 都可以附加到该节点。 -
是的,我也想到了。我正在尝试修改查询和代码,以便顶级 cmets 将 post id 作为父 id,但 make-tree 函数似乎不喜欢那样。我认为这是我可以通过让查询也选择帖子并将其作为树中的第一个节点来解决的问题。