Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Waterline associations, change foreign key?

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?

like image 566
InternalFX Avatar asked Apr 03 '14 17:04

InternalFX


1 Answers

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.

like image 116
sgress454 Avatar answered Oct 02 '22 22:10

sgress454