user3630910
user3630910

Reputation: 11

How to achieve many to many relationship among 2 tables in rethinkdb?

So this is quite basic in webapps but I am unable to figure out the solution in rethinkdb as its my first time working with DBs. One post has many tags and one tag has many posts under it. I want to be able to retrieve all the posts when I click on a tag and all the tags when I click on a post.

How do I achieve this with rethinkdb and is 2 the ideal number of tables I should use for this task?

p.s. : If anyone from rethinkdb team sees this, I suggest putting more examples in your api, especially something other then DC or Marvel universe, which a general audience can relate to. Many people might start using rethinkdb to explore databases for the first time and just looking at api or turorial might not be good enough for "non-trivial" tasks.

Thanks

Upvotes: 0

Views: 737

Answers (1)

neumino
neumino

Reputation: 4353

You can basically do the same thing as in SQL, take a look at the "Many to many relations" section: http://www.rethinkdb.com/docs/table-joins/

You also might be interested in the "Data modeling" article: http://www.rethinkdb.com/docs/data-modeling/

If you want to retrieve a full document with a nested array of tags, you can also do something like

r.table("posts").map(function(post) {
    return post.merge({
        tags: r.table("postsTagsLinks").getAll(post("id"), {index: "postId"}).map(function(link) {
            return r.table("tags").get(link("tagId"))
        }).coerceTo("ARRAY")
    })
})

Upvotes: 2

Related Questions