What is a Smart Relationship?
Sometimes, you want to create a virtual relationship between two set of data that does not exist in your database. A concrete example could be creating a relationship between two collections available in two different databases. Creating a Smart Relationship allows you to customize with code how your collections are linked together.Create a BelongsTo Smart Relationship
On the Live Demo example, we have an order whichbelongsTo a customer which belongsTo a delivery address. We’ve created here a BelongsTo Smart Relationship that acts like a shortcut between the order and the delivery address.
A BelongsTo Smart Relationship is created like a Smart Field with the reference option to indicate on which collection the Smart Relationship points to. You will also need to code the logic of the search query.
- SQL
- Mongoose
- Rails
- Django
- SQL
- Mongoose
- Rails
- Django
- Laravel
Upon browsing, an API call is triggered when accessing the data of the HasMany relationships in order to fetch them asynchronously. In the following example, the API call is a GET on Option2: using raw SQLWe’ll use raw SQL query and Sequelize to count and find all customers who bought the current product (buyers).Then, you should handle pagination in order to avoid performance issue. The API call has a query string available which gives you all the necessary parameters you need to enable pagination.Finally, you don’t have to serialize the data yourself. The Forest agent already knows how to serialize your collection (
/products/:product_id/relationships/buyers.Option 1: using Sequelize ORMWe’ll use the findAll and count methods provided by Sequelize to find and count all customers who bought the current product (buyers).Then, you should handle pagination in order to avoid performance issue. The API call has a query string available which gives you all the necessary parameters you need to enable pagination.Finally, you don’t have to serialize the data yourself. The Forest agent already knows how to serialize your collection (customers in this example). You can access to the serializer through the recordsGetter.serialize function.customers in this example). You can access to the serializer through the recordsGetter.serialize function.