Chinese Documentation : HasAndBelongsToMany relations

Overview

A hasAndBelongsToMany relation creates a direct many-to-many connection with another model, with no intervening model. For example, in an application with assemblies and parts, where each assembly has many parts and each part appears in many assemblies, you could declare the models this way:

Defining a hasAndBelongsToMany relation

Use slc loopback:relation to create a relation between two models.  You'll be prommpted 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 an excerpt from a model JSON file for a student model, expressing a hasAndBelongsToMany relation between student and class models:

/common/models/student.json
{
  "name": "Student",
  "plural": "Students",
  "relations": {
    "classes": {
      "type": "hasAndBelongsToMany",
      "model": "Class"
    },
...

You can also define a hasAndBelongsToMany relation in code, though this is not recommended in general.  For example:

/common/models/student.js
Class.hasAndBelongsToMany(Student);
Student.hasAndBelongsToMany(Class);

Methods added to the model

Once you define a "hasAndBelongsToMany" relation, LoopBack adds methods with the relation name to the declaring model class’s prototype automatically, for example: assembly.parts.create(...).
Example methodDescription
assembly.parts(filter, function(err, parts) {
...
});
Find parts for the assembly.
var part = assembly.parts.build(data);
Build a new part.
assembly.parts.create(data, function(err, part) {
...
});
Create a new part for the assembly.
assembly.parts.add(part, function(err) {
...
});
Add a part to the assembly.
assembly.parts.remove(part, function(err) {
...
});
Remove a part from the assembly.
assembly.parts.findById(partId, function(err, part) {
...
});
Find a part by ID.
assembly.parts.destroy(partId, function(err) {
...
});
Delete a part by ID.

Attachments: