hydra
Search…
Variant relations
Define variant types with relations
Variant types support entity relationship in a different way unlike the normal entity relationship. There are some limitations with variant relations:
  • Only one-to-many and many-to-one relations are supported
  • Reverse lookup is not supported
Let's take a look an example:
  1. 1.
    Schema: in the schema below there are two variant types with the relations
1
type BoughtMemberEvent @entity {
2
id: ID!
3
name: String
4
handle: String!
5
}
6
7
type InvitedMemberEvent @entity {
8
id: ID!
9
name: String
10
handle: String!
11
}
12
13
type MemberInvitation @variant {
14
event: InvitedMemberEvent!
15
}
16
17
type MemberPurchase @variant {
18
event: BoughtMemberEvent!
19
}
20
21
union MemberSource = MemberInvitation | MemberPurchase
22
23
type Member @entity {
24
id: ID!
25
isVerified: Boolean!
26
handle: String!
27
source: MemberSource!
28
}
Copied!
  1. 1.
    Mappings: insert data into database
For variant relations to work an additional field is added to variant type which is db only field (which means it is not visible in the graphql API). This field is will be generated from relation field name + 'id' ie. in the schema above relation name is event so the auto generated field name is eventId. This field is not optional and mapping author must set it properly.
1
async function handle_Member(db: DB, event: SubstrateEvent) {
2
// Create an event from BoughtMemberEvent or MemberInvitation and save to db
3
let event = new InvitedMemberEvent({ handle: 'joy' })
4
event = await db.save<InvitedMemberEvent>(event)
5
6
// Create variant instance and set eventId property
7
const invitation = new MemberInvitation()
8
// Auto generated property, it holds primary key of the related entity
9
invitation.eventId = event.id
10
11
// Create new member and set the source property
12
const member = new Member({ handle: 'hydra', isVerified: true })
13
member.source = invitation
14
await db.save<Member>(member)
15
}
Copied!
  1. 1.
    Query: fetch all members' source:
1
query {
2
members {
3
source {
4
__typename
5
... on MemberInvitation {
6
event {
7
id
8
name
9
handle
10
}
11
}
12
}
13
}
14
}
Copied!
Last modified 8mo ago
Copy link