Backendless Support
 
Answered

How to make a many-to-many relation?

Let's say I have a table 'Users' and a table 'Interests'.

Interests have some "predefined" rows, with 'name' field, like:

1 | Cars

2 | Pets

3 | Music

A user may have multiple interests. But I didnt find any many-to-many relations.

On the forum I found that I can create a one-to-many relations both in Users and Interests, but when I try, for example, to create such in Users, it creates an additional field in Interests, which can contain only one user relation. Same for Interests table.

In the end I have Users with 'interests' field and 'Interests.users' field, and Interests with 'users' and 'Users.interests'.

I do not actually understand how it will work and what to do.

Maybe the best way could be some kind of ENUM type, but there is no such.

What can be possible solutions?

Leave a Comment

Comments (1)

photo
1

Hey Vladimir

As I understand you wanna have relations between Users and Interests tables, and then getting all "interests" for one "user" and getting all "users" for one "interest", so there is a really easy way

1) create a new table "Interests"

2) select "Users" table and go to Table Schema and Permissions

3) add new Column (name = 'interests'; type = 'DATA_REF' relatedTable = 'Interest'; 1:N )

4) go to DataBrowser, select "Interests" table and create a few "interest" record

5) select "Users" table and create a few user

6) you can see "interest" column, add interests for each users

Ok, now we have what you want

let's try to get users with relations:

1) select "Users" table and go to REST Console section (it will show you how to retrieve user or users with "interests")

2) click at "GET" button ( you will see all users but without "interests")

3) now if you want to get one user you need to set "objectId" or leave the field empty for get all users

4) for load "interests" you have 3 variants

- specify loadRelations param

- specify relationsDepth param

- or enable "autoload" checkbox in Users table "interest" column head

in screenshot you can see "loadRelations"

5) click "GET" button and now you can see that user/users have "interests" prop array of "Interests" records

Now let's try to get all users which have some "Interest"

1) select "Interests" table

2) goto REST Console

3) input in "Where" field this one Users[interests].objectId='2F1C6C6C-059A-E1DF-FF31-3F81D3148F00' ( don't forget to replace userObjectId with your)

4) click at GET button, and as result you can see all users which have the "interest"

I recommend to you read this docs https://backendless.com/documentation/data/rest/data_relations_retrieve.htm

Also I've attached a few screenshots for you

Hope it's helped you

Regards, Vlad