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;
  5. @ManyToMany(_Enrollment)
  6. List<_Student> get students;
  7. }
  8. @orm
  9. @serializable
  10. abstract class _Student extends Model {
  11. String get name;
  12. int get year;
  13. @ManyToMany(_Enrollment)
  14. List<_Class> get classes;
  15. }
  16. @orm
  17. @serializable
  18. abstract class _Enrollment {
  19. @belongsTo
  20. _Student get student;
  21. @belongsTo
  22. _Class get class_;
  23. }