Sails.js / Waterline Foreign Key Combination Associations

I need a model called "Package" that can have one or more children of several different types. For example, a package might contain guides as well as forms and other types of content (some of which will be added later). Each of these content items from different tables can be in multiple packages. So I have the following scheme:

Package table
=============
id
name
....

PackageContent table
=============
id
packageId
contentType
contentId

Guide table
=============
id
name
...

Form table
=============
id
name

      

How can I determine the content association for my packages in the Package.js model file in sails.js? I was unable to find information about foreign key combination in sails.js or Waterline files. I would like to find something like:

// models/Package.js
module.exports = {
  attributes = {
    name: 'text',

    ....

    content: {
      through: 'PackageContent',
      collection: contentType,
      via: 'contentId'
    }
  }
};

      

+3


source to share


1 answer


I have a similar problem recently. My solution is to create different foreign keys in the intermediate model and set the attributes as required: false. In your example, the PackageContent table might look like this:

 //PackageContent.js
 module.exports={
    attributes={
        package:{
            model:'package',
        },
        guide:{
            model:'guide'
            require:false
        },
        form:{
            model:'form'
            require:false
        }
        //other attributes...
    }
}

      



To avoid duplicate package + content combination, you may need to write a beforeValidate method to check for duplication. I'm not sure if this is "good design", but it solves the problem

+1


source







All Articles