Search code examples
dartaqueduct

Use @Relate and unique


How can I use Relate and unique using aqueduct ORM?

In my code I want that the userapp be unique? If I try to put @Column(unique: true) I receive a error like this:

*** Relationship 'userapp' on '_Professional' cannot both have 'Column' and 'Relate' metadata. To add flags for indexing or nullability to a relationship, see the constructor for 'Relate'.

My code below:

class Professional extends ManagedObject<_Professional> implements _Professional {}

class _Professional {

  @primaryKey
  int id;
  @Relate(#professionals)
  Userapp userapp;
  @Column(defaultValue: 'true')
  bool active;  

  ManagedSet<ProfessionalSpecialty> professionalSpecialties;

}

Solution

  • Whether the foreign key column underlying userapp is unique or not is determined by the inverse relationship property. In this case, the inverse is Userapp.professionals.

    If Userapp.professionals is of type Professional, then a unique constraint is added to userapp; this is a 'has-one' relationship.

    If Userapp.professionals is of type ManagedSet<Professional>, no unique constraint is applied; this is a 'has-many' relationship.

    I'd guess that because you are using the plural form (professionals) that you are declaring a ManagedSet<Professional>. Change the declaration in the _Userapp table definition and make sure your inverse matches in _Professional:

    class _Userapp {
      ...
      Professional professional;
    }
    class _Professional {
      ...
      @Relate(#professional)
      Userapp userapp;
    
    }