Preliminary checklist
Problem
It would be very intuitive where a Model can reference relations, here is an example use case:
@Table({ name: 'follows', edge: true })
export class Followers extends Model
{
@Field({ name: 'in' })
inside!: User;
out!: User;
}
@Table({ name: 'follows', edge: true })
export class Following extends Model
{
@Field({ name: 'in' })
inside!: User;
out!: User;
}
@Table<User>({
name: 'user',
permissions: ({ username }) => [
[['CREATE', 'UPDATE', 'SELECT'], true],
['DELETE', AdminScope]
],
auditable: true,
})
export class User extends Model
{
@Field({ index: 'unique' })
username: string;
@Field({ assert: 'email', name: 'email_address', index: 'unique' })
email?: string;
bestFriend?: User;
followers?: Followers[];
following?: Following[];
}
being able to select, relational fields via the select method
eg. User.select(['username', 'followers', 'following']).build()
SELECT username, <-follows<-user as followers, ->follows->user as following FROM user
also to be able to fetch relational fields via the fetch method
eg. User.select(['username', 'followers', 'following']).fetch(['followers', 'following']).build();
there are several issues which need to be addressed
- the schema generator must know how to handle the relational fields (i.e do not mistake them for record fields)
- the select builder must also know how to differentiate between relational and record fields
one solution could be to create a new decorator called @relational
this decorator would be used to decorate the relational fields
@relational(Followers) (could also potentially add more props to this decorator)
the schema generator would then know to ignore these fields
the select builder would also know to ignore these fields
another solution could be to add a new property to the @field decorator
eg. @field({ relation: Followers })
a third solution could be to expand the current select method to accept an instance of a select builder
eg. User.select(['username')]).select(Followers.select())
or expand the in, out logic to handle the relational query
However, further investigation is needed on how one might reference deeply nested relations and an alternative API maybe necessary than the one currently suggested.
Solution
Relation references could be tagged with a decorator i.e. @FieldRelation()
and therefore be usable in Models:
export class Account extends Model
{
@FieldRelation({ direction: 'in' })
friends: Friend[]
}
Alternatives
No response
Contribution
No, I cannot contribute further
Keywords
relations, model, query, API