Suni
Suni

Reputation: 168

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

Upvotes: 1

Views: 68

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12684

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)

Upvotes: 1

Graphileon
Graphileon

Reputation: 5385

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)
  )

Upvotes: 0

Related Questions