I am new to neo4j and currently using Neo4jphp library with cypher to store and retrieve nodes. My logic is fairly simple. I want to get a node (post) and get all its likes (count of likes) and all comments (nodes) with their commenters (nodes of label user) and be able to parse the ResultSet in a php array to later encode it to Json.
The cypher statement I'm using is:
MATCH (user:User)-[:POSTED]->(post)
WHERE post.UserID = '13'
AND id(post) = 106
OPTIONAL MATCH ()-[rel:LIKES]-(post)
OPTIONAL MATCH (post)-[:HAS]-(comment:Comment)<-[:COMMENTED]-(commenter:User)
RETURN user, post, count(rel) AS Likes, rel, comment, commenter
The match retrieves all nodes correctly (this post has no likes though):
(source: bookintransit.com)
How do I get the correct representation of this graph using the library? Also note that for simplicity I retrieved one post node (id:106) in this example. But I'd like to retrieve a list of posts when I use the code in my application.
This is the php code I'm using:
$queryString = "MATCH (user:User)-[:POSTED]->(post) WHERE post.UserID = {qUser} OPTIONAL MATCH ()-[rel:LIKES]-(post) OPTIONAL MATCH (post)-[:HAS]-(comment:Comment)<-[:COMMENTED]-(commenter:User) RETURN user, post,count(rel) AS Likes, rel, comment, commenter ORDER BY post.TS DESC LIMIT ".$NumberOfPosts;
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString, array('qUser' => $UserID));
$result = $query->getResultSet();
if(count($result)>0){
foreach($result AS $row){
// How do I get the correct graph in a php array to parse to json
}
I think you are looking for something like this. Find all the posts of a user. With each post optionally find all of the comments and like for each; put the comments and related users into a collection; count the number of likes; and return it all per post.