Conceptually similar to: http://guides.rubyonrails.org/association_basics.html#polymorphic-associations
Example models: Picture, Author, Reader.
The usual options apply, for example: as: 'photos'
to specify a different relation name/accessor.
Author.hasMany(Picture, { polymorphic: 'imageable' });
Reader.hasMany(Picture, { polymorphic: { // alternative syntax
as: 'imageable', // if not set, default to: reference
foreignKey: 'imageableId', // defaults to 'as + Id'
discriminator: 'imageableType' // defaults to 'as + Type'
} });
Because the related model is dynamically defined, it cannot be declared upfront.
So instead of passing in the related model(name), the name of the polymorphic relation is specified.
Picture.belongsTo('imageable', { polymorphic: true });
// Alternatively, use an object for setup:
Picture.belongsTo('imageable', { polymorphic: {
foreignKey: 'imageableId',
discriminator: 'imageableType'
} });
This requires an explicit 'through' model, in this case: PictureLink
The relations Picture.belongsTo(PictureLink)
and
Picture.belongsTo('imageable', { polymorphic: true });
will be setup automatically.
The same is true for the needed properties on PictureLink.
Author.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' });
Reader.hasAndBelongsToMany(Picture, { through: PictureLink, polymorphic: 'imageable' });
// Optionally, define inverse hasMany relations (invert: true):
Picture.hasMany(Author, { through: PictureLink, polymorphic: 'imageable', invert: true });
Picture.hasMany(Reader, { through: PictureLink, polymorphic: 'imageable', invert: true });
As can be seen here, you can specify as: 'avatar'
to explicitly set the name of the relation. If not set, it will default to the polymorphic name.
Picture.belongsTo('imageable', { polymorphic: true });
Author.hasOne(Picture, { as: 'avatar', polymorphic: 'imageable' });
Reader.hasOne(Picture, { polymorphic: { as: 'imageable' } });
@fabien /cc @raymondfeng
Would you be so kind as to review the docs at http://docs.strongloop.com/display/LB/Creating+model+relations#Creatingmodelrelations-Relationoptions ? They basically duplicate the above info for the new relation options.
I have one specific question, re:
"Most"? Which ones DON'T they apply to?
I would appreciate any other examples of suggestions for clarifying these docs.