简体   繁体   中英

How can I create nodes and create a one-to-many relationship another newly created node?

    UNWIND $likedMovies AS likedMovie
    MERGE (lm:LikedMovie {
      id: likedMovie.id,
      name: likedMovie.name,
    })

    CREATE p = (:Person $person)-[:LIKES]->(lm)

This doesn't solve my problem as it creates a new Person for every likedMovie Instead I want the single Person to be related to all the likedMovie 's

I also tried this:

    UNWIND $likedMovies AS likedMovie
    MERGE (lm:LikedMovie {
      id: likedMovie.id,
      name: likedMovie.name,
    })

    CREATE p = (:Person $person)

    FOREACH (lm in likedMovie | 
       MERGE (p)->[:LIKES]-(lm)
    )

But, it's giving me an error that p is a Path and needs to be a Node

When you assigned p = (:Person), it created a path with nodes in it. But if you assign a variable (p:Person), the variable p is the node itself. Thus, you can use it to create your relationship with p one-to-many.

CREATE (p:Person $person)
UNWIND $likedMovies AS likedMovie
WITH p, likedMovie
MERGE (p)-[:LIKES]->(likedMovie)

This template should do it (although I do not know what is in $person )

  CREATE (p:Person {name: $person})

  FOREACH(m in $likedMovies |
      MERGE (lm:LikedMovie {id: m.id, name: m.name})
      MERGE (p)-[:LIKES]->(lm)
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM