Relational modeling is one of the most commonly-used features of sql databases -after all, it is the namesake of the term “relational database.”

Angel supports the following kinds of relations by means of annotations on fields:

  • @hasOne (one-to-one)
  • @hasMany (one-to-many)
  • @belongsTo (one-to-one)
  • @manyToMany (many-to-many)

By default, the keys for columns are inferred automatically.In the following case:

1. @orm
2. @serializable
3. abstract class _Wheel extends Model {
4. @belongsTo
5. Car get car;
6. }

The local key defaults to car_id, and the foreign key defaults to id.You can manually override these:

1. @BelongsTo(localKey: 'carId', foreignKey: 'licenseNumber')
2. Car get car;

The ORM computes relationships by performing JOINs, so that even complexrelationships can be fetched using just one query, rather than multiple.

Many-to-many Relationships

A very common situation that occurs when using relational databases is where two tablesmay be bound to multiple copies of each other. For example, in a school database, each studentcould be registered to multiple classes, and each class could have multiple students taking it.

This is typically handled by creating a third table, which joins the two together.In the Angel ORM, this is relatively straightforward:

1. @orm
2. @serializable
3. abstract class _Class extends Model {
4. String get courseName;

6. @ManyToMany(_Enrollment)
7. List<_Student> get students;
8. }

10. @orm
11. @serializable
12. abstract class _Student extends Model  {
13. String get name;
14. int get year;

16. @ManyToMany(_Enrollment)
17. List<_Class> get classes;
18. }

20. @orm
21. @serializable
22. abstract class _Enrollment {
23. @belongsTo
24. _Student get student;

26. @belongsTo
27. _Class get class_;
28. }