The @hasOne
and @hasMany
directives do not support referencing a model which then references the initial model via @hasOne
or @hasMany
if DataStore is enabled.
DataStore has the capability to handle relationships between Models, such as has one, has many, belongs to. In GraphQL this is done with the @hasOne
, @hasMany
and @index
directives as defined in the GraphQL Transformer documentation.
For the examples below with DataStore let's add a new model to the sample schema:
Saving relationsIn order to save connected models, you will create an instance of the model you wish to connect and pass its ID to DataStore.save
:
Models with one-to-many connections are lazy-loaded when accessing the connected property, so accessing a relation is as simple as:
The connected properties are of type List<M>
, where M
is the model type, and that type is a custom Swift Collection, which means that you can filter
, map
, etc:
When you delete a parent object in a one-to-many relationship, the children will also be removed from the DataStore and mutations for this deletion will be synced to cloud. For example, the following operation would remove the Post with id 123 as well as any related comments:
However, in a many-to-many relationship the children are not removed and you must explicitly delete them.
Many-to-many relationshipsFor many-to-many relationships, you can use the @manyToMany
directive and specify a relationName
. Under the hood, Amplify creates a join table and a one-to-many relationship from both models.
Join table records must be deleted prior to deleting the associated records. For example, for a many-to-many relationship between Posts and Tags, delete the PostTags join record prior to deleting a Post or Tag.
This example illustrates the complexity of working with multiple dependent persistence operations. The callback model is flexible but imposes some challenges when dealing with such scenarios. Prefer to use the Combine model if your app supports iOS 13 or higher. If not, the recommendation is that you use multiple functions to simplify the code.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4