14

This model gives me the effect I want at the expense of duplicated data and general uglyness:

//Example
var Example = {
    attributes: {
        foo: { 
            type: 'string',
            required: true
        },
        bar: {
            type: 'string',
            required: true,
        },
        baz: {
            type: 'integer',
            required: true,
            min: 1
        },
        foobar: {
            type: 'string',
            unique: true
        }
    },
    beforeValidation : function(values,cb) {
        values.foobar = values.foo+values.bar;
        cb();
    }
};
module.exports = Example;

Is there a better strategy for creating a composite unique key?

user2458080
  • 989
  • 8
  • 17
  • I am also looking for an answer to this problem, but in waterline. Did you use this technique and did it work for you? Or did you use a database-specific solution (not something I'd want to pursue)? – Charlie Oct 18 '15 at 23:03

1 Answers1

7

There's no way to do this directly in sails see https://github.com/balderdashy/waterline/issues/221. The best solution is to do this directly in the db you plan to use.

JohnGalt
  • 2,851
  • 2
  • 21
  • 29
  • 3
    The problem with doing this in the database is that, when you want to reference the composite primary key as a foreign key in another table, the Waterline ORM will do nothing for you. You'll to end up implementing that part of the ORM yourself. The asker's solution is likely better in this case than implementing it at the database level. – Grant Robert Smith May 10 '17 at 18:06