本文介绍了密码中的嵌套has_many关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个嵌套的has_many关系,试图映射到json结果.
I have a nested has_many relationship that I'm trying to map to a json result.
博客中的以下示例显示了我想做的事情,除了它不是嵌套的
The following example from the blog shows the kind of thing I want to do, except it's not nested
MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child)
RETURN
{name:a.name, kids:collect(child.name)} as document
我想要的是这样的
MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child)-[:has_read]->(book)-[:has_chapter]->(chapter)
RETURN
{name:a.name, kids:collect({"name":child.name, has_read:collect(book)})} as document
在这种情况下,我想返回一个结构如下的json对象:
In this case I would like to return a json object of a structure like this:
{
"name": "Andres"
"kids": [
{
"name":"Bob"
"has_read": [
{
"name":"Lord of the Rings",
"chapters": ["chapter1","chapter2","chapter3"]
},
{
"name":"The Hobbit",
"chapters": ["An unexpected party","Roast mutton"]
}
]
},
{
"name":"George"
"has_read": [
{
"name":"Lord of the Rings",
"chapters": ["chapter1","chapter2","chapter3"]
},
{
"name":"Silmarillion",
"chapters": ["chapter1","chapter2"]
}
]
}
]
}
推荐答案
可以尝试:
如果您与该章保持一致,则需要与众不同collect(distinct book.title)
否则.
if you keep the match to the chapter you will need distinctcollect(distinct book.title)
otherwise not.
MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child),
(child)-[:has_read]->(book)-[:has_chapter]->(chapter)
WITH a,child,collect(distinct book.title) as books
RETURN
{name:a.name,
kids:collect({name:child.name,
has_read:books})} as document
哦,如果您也想在结果中包括这些章节,则只需添加一个带有:)
Oh and if you want to include the chapters in the results too, then just add another with :)
MATCH (a:Person { name: "Andres" })-[:FATHER_OF]->(child),
(child)-[:has_read]->(book)-[:has_chapter]->(chapter)
WITH a,child, {title: book.title, chapters: collect(chapter.title)} as book_doc
WITH a,child, collect(book_doc) as books
RETURN
{name:a.name,
kids:collect({name:child.name,
has_read:books})} as document
请参阅: http://console.neo4j.org/r/kua2pi
这篇关于密码中的嵌套has_many关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!