When I add a belongs_to model to the field, does it also add some kind of hidden id field? What about has_many, does it also add a hidden field?

When I add a belongs-to model to the field, does it also add some kind of hidden id field? What about has-many, does it also add a hidden field?

When you create a belongs_to field, The JourneyApps Platform will create an additional field to your model containing the ID of the parent object. So for example if you had the below syntax:

<belongs-to model="region"/>

the platform will add a field/column called region_id to your model. Note that fields created in this way can both be set and read in JS.

The has-many is just a helper relationship and does not create any additional field. The best way to explain it is by analogy using SQL. Continuing with the above example, if the parent model is region and the child object is branch, you would have the following on the region model:

<has-many model="branch" name="branches" />

In this case when you access region.branches, the platform uses the following query object to fetch the children:

SELECT * FROM BRANCHES 
WHERE REGION_ID = region.id

where region.id is the ID of the region object when accessing region.branches.

2 Likes

Does this mean I can use the region_id to set the relationship as well, for instance user branch.region_id = region.id or can I only use branch.region(region); to set a relationship? What would you consider as better?

@AntonVanZyl Yes, you can use region_id as a setter as per your example. It’s personal preference as to which you consider better and there is no performance difference. However there are certain use cases where you need to use the property setter instead of the function call, so it’s good to have in your back pocket.