leonixyz
leonixyz

Reputation: 1192

Loopback: many-to-many relation, cannot get opposite

I just started using Loopback, and defined two models which should be bound by a trivial many-to-many relation.

The first model is Customer, the second model is Pet.

Each Customer can have different Pets, and each Pet can be owned by different Customers.

I create the relation using loopback-cli, and define it on the Customer model, having the Pet model as reference. The only change in the code is:

/* customer.json */
"relations": {
  "Pets": {
    "type": "hasAndBelongsToMany",
    "model": "Pet",
    "foreignKey": ""
  }
}

After this, I find a new set of REST endpoints for various actions of resources like /customers/{customerId}/pets.

How do I get also the opposite "side" of the relation, which in terms of REST api would be /pets/{petId}/customers?

I don't want to create a new relation, nor a new model. I just want to reuse the current MySQL table CustomerPet that already contains the information I need.

Thanks in advance

Upvotes: 1

Views: 76

Answers (1)

leonixyz
leonixyz

Reputation: 1192

The proper way to deal with a hasAndBelongsToMany relation is to create it in both directions with the cli tool:

  • a Pet hasAndBelongsToMany Customers
  • a Customer hasAndBelongsToMany Pets

This translates in having two different tables in the database: PetCustomer and CustomerPet.

Then, th REST api deals with both tables automatically when a new relation between two entities is created. There are two ways to do that:

  • creating a new related entity, e.g. by POSTing a new pet to /customers/{:customerId}/pets
  • creating a reference between two existing entities, e.g. by PUTting (an empty body is enough) to /customers/{:customerId}/pets/rel/{:petId}

I guess duplicating the database table holding the many-to-many relation is the price to have such a flexible and easy-to-use tool like loopback.

Upvotes: 1

Related Questions