Search code examples
node.jsormmany-to-manyloopback4

Can I create a unique constraint on Loopback4's hasManyThrough (M:M) table


Preamble

I'm somewhat new to Loopback 4, and I have successfully created 2 working CRUD controllers, repositories, models, etc. I have Users and Organizations, and I am have successfully created a M:M relation between Users and Organizations using the relation generator. So, I can create a user, create an organization, and separately I can link them together in a many-to-many table called "membership". All of this follows (as far as I know) loopback best practices per their docs.

Question:

How do I make sure that each record in the membership table is unique?

here's an example of my table with duplicates

For example, User #1, Jeff, joins Organization #1, Amazon. Some erroneous code then attempts to add Jeff to Amazon a 2nd time, I want this to fail.

I was thinking I could simply check the database if the record exists, but it seems cleaner to add this constraint to the model, so that any attempted insert would fail if duplicate. I have dug around in the docs and haven't found anything.

Any help is appreciated!


Solution

  • In database design, a unique constraint would be enforced by a compound/composite key on the junction table. This would enforce a unique pair of orgId and userId.

    Hence, the junction table should have only 2 columns:

    • orgId
    • userId

    To create a composite key in LoopBack 4, update the through model as follows:

    // Some parts were omitted for bevity
    
    @model()
    export class OrgUser extends Entity {
      @property({id: 1})
      orgId: number;
      
      @property({id: 2})
      userId: number;
    
      constructor(data?: Partial<OrgUser>) {
        super(data);
      }
    }