Page Contents

Overview

hasMany relation builds a one-to-many connection with another model. You’ll often find this relation on the “other side” of a belongsTo relation. This relation indicates that each instance of the model has zero or more instances of another model. For example, in an application with customers and orders, a customer can have many orders, as illustrated in the diagram below.

</figure>

The target model, Order, has a property, customerId, as the foreign key to reference the declaring model (Customer) primary key id.

Defining a hasMany relation

Use apic loopback:relation to create a relation between two models. The tool will prompt you to enter the name of the model, the name of related model, and other required information. The tool will then modify the model definition JSON file (for example, common/models/customer.json) accordingly.

For more information, see Relation generator.

For example, here is the model JSON file for the customer model in loopback-example-relations:

common/models/customer.json

{
  "name": "Customer",
  "base": "PersistedModel",
  ...
  "relations": {
    "orders": {
      "type": "hasMany",
      "model": "Order",
      "foreignKey": "customerId"
    },
  ...

Alternatively, you can define the relation in code, though in general this is not recommended:

common/models/customer.js

Customer.hasMany(Review, {as: 'reviews', foreignKey: 'authorId'});

If not specified, LoopBack derives the relation name and foreign key as follows:

  • Relation name: The plural form of the camel case of the model name; for example, for model name “Order” the relation name is “orders”.
  • Foreign key: The camel case of the declaring model name appended with Id, for example, for model name “Customer” the foreign key is “customerId”.

Methods added to the model

Once you define a “hasMany” relation, LoopBack adds a method with the relation name to the declaring model class’s prototype automatically. For example: Customer.prototype.orders(...).

Example method Description
customer.orders([filter],
  function(err, orders) {
...
});
Find orders for the customer, optionally using provided [filter](Querying-data.html)
var order = customer.orders.build(data);

Or equivalently:

var order = new Order({customerId: customer.id, ...});
Build a new order for the customer with the customerId to be set to the id of the customer. No persistence is involved.
customer.orders.create(data,
  function(err, order) {
...
});

Or, equivalently:

Order.create({customerId: customer.id, ...},
  function(err, order) {
...
});
Create a new order for the customer.
customer.orders.destroyAll(function(err) {
...
});
Remove all orders for the customer.
customer.orders.findById(orderId,
  function(err, order) {
...
});
Find an order by ID.
customer.orders.destroy(orderId,
  function(err) {
...
});
Delete an order by ID.