Waterline associations, change the foreign key?

The latest waterline now supports associations. Here is a one-to-many example

// A user may have many pets
var User = Waterline.Collection.extend({

  identity: 'user',
  connection: 'local-postgresql',

  attributes: {
    firstName: 'string',
    lastName: 'string',

    // Add a reference to Pets
    pets: {
      collection: 'pet',
      via: 'owner'
    }
  }
});

var Pet = Waterline.Collection.extend({

  identity: 'pet',
  connection: 'local-postgresql',

  attributes: {
    breed: 'string',
    type: 'string',
    name: 'string',

    // Add a reference to User
    owner: {
      model: 'user'
    }
  }
});

This creates a field called ownerin the pet collection. This would be good, except for working with an existing database. which calls it a foreign key owner_id.

Can I override the field name used in the database?

+4
source share
1 answer

You can change the column name used for any attribute of the model by setting the property columnName:

  attributes: {
    breed: 'string',
    type: 'string',
    name: 'string',

    // Add a reference to User
    owner: {
      columnName: 'owner_id',
      model: 'user'
    }
  }

, Sails Waterline, /api/models , . User.js:

module.exports = {

   attributes: {
      breed: 'string',
      type: 'string',
      name: 'string',

      // Add a reference to User
      owner: {
         model: 'user',
         columnName: 'owner_id'
      }
   }
}

Sails/Waterline , .

+6

Source: https://habr.com/ru/post/1534892/


All Articles