The latest waterline now supports associations. Here is an example of a one-to-many
// 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 owner on the pet collection. This would be fine except for working with an existing DB. which calls it's foreign key owner_id.
Is there anyway to override the field name used in the database?
You can change the column name used for any model attribute by setting the columnName property:
  attributes: {
    breed: 'string',
    type: 'string',
    name: 'string',
    // Add a reference to User
    owner: {
      columnName: 'owner_id',
      model: 'user'
    }
  }
Note also that when defining a model in Sails, you shouldn't extend from Waterline directly, but simply save the model file in /api/models with the appropriate name, e.g. User.js:
module.exports = {
   attributes: {
      breed: 'string',
      type: 'string',
      name: 'string',
      // Add a reference to User
      owner: {
         model: 'user',
         columnName: 'owner_id'
      }
   }
}
and let Sails / Waterline handle the identity and connection for you unless you really want to override the defaults.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With