Chinese Documentation : HasOne relations

Icon

This article is currently incomplete and in-progress. See LoopBack issue #718.

Overview

hasOne relation sets up a one-to-one connection with another model, such that each instance of the declaring model "has one" one instance of the other model. 

Icon

Example TBD

REVIEW COMMENT from Rand

Add: example and description of foreign/primary keys, etc.

How is hasOne different than belongsTo ?

See https://groups.google.com/forum/#!topic/loopbackjs/raza2iRvVns

Defining a hasOne 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:

REVIEW COMMENT from Rand
Fix example below to correspond to example given above.
/common/models/model.json
    "foos": {
      "type": "hasOne",                                                                                       
      "model": "bar",
      "foreignKey": "baz"
    }
...
/common/models/model.js
User.belongsTo(Project, {foreignKey: ‘ownerId’});
REVIEW COMMENT from Rand
Is below true for hasOne?

If the declaring model doesn’t have a foreign key property, LoopBack will add a property with the same name.  The type of the property will be the same as the type of the target model’s id property.

If you don’t specify them, then LoopBack derives the relation name and foreign key as follows:

  • Relation name: Camel case of the model name, for example, for the "Customer" model the relation is "customer".
  • Foreign key: The relation name appended with ‘Id’, for example, for relation name "customer" the default foreign key is "customerId".

Methods added to the model

Once you define the hasOne relation, LoopBack automatically adds a method with the relation name to the declaring model class’s prototype, for example: Order.prototype.customer(...).

Depending on the arguments, the method can be used to get or set the owning model instance.

REVIEW COMMENT from Rand
Fill in table below.

 

 

Example methodDescription