Reputation: 2810
On sailsjs.org's documentation, a one to many relationship for the owning side is defined like this
//user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
pets:{
collection: 'pet',
via: 'owner'
}
}
}
'pet' is a constant, with a consistent schema on SQL databases. What if I want to have a superclass pet and subclasses with unique attributes(different number of rows)? Say I have an octopus and a dog. Dogs have 4 legs and 2 ears. Octopus have 8 tentacles. The only commonality will be abstracted into the pet class(color, name, age).
If this is not possible, I would have to resort to something like this no?
//user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
dogs:{
collection: 'dog',
via: 'owner'
},
octopuses:{
collection: 'octopus',
via: 'owner'
}
}
}
However, this could get quite messy if I wanted to introduce more pets like eagle(can fly), parrot(can talk), and would result in many nulls if I was to use a SQL database. Perhaps mongoDB would be ideal for this?
Upvotes: 1
Views: 1316
Reputation: 2416
In Waterline each model is treated as a table in a SQL database or a Collection in Mongo. If a Dog will have completely different attributes from an Octopus then yes you would break those into separate tables and link them to the User. I think the easiest way would to just add a type
attribute to the Pet model.
// user.js
module.exports = {
attributes: {
name:'STRING',
age:'INTEGER',
pets:{
collection: 'pet',
via: 'owner'
}
}
}
// pet.js
module.exports = {
attributes: {
name:'STRING',
type: 'STRING',
owner:{
model: 'user'
}
}
}
This would allow queries such as:
User.find().populate('pets', { type: 'dog' });
Another option would be to store the pet attributes in a json object. This isn't currently searchable but would allow you to store various things about the pets in a denormalized fashion.
// pet.js
module.exports = {
attributes: {
name:'STRING',
type: 'STRING',
characteristics: {
type: 'json'
},
owner:{
model: 'user'
}
}
}
Which would allow you to have pets that look like the following:
[{
id: 1,
name: 'fluffy',
type: 'dog',
characteristics: {
food: 'mice',
limbs: 4,
fur: 'white'
},
owner: 1
},
{
id: 2,
name: 'inky',
type: 'octopus',
characteristics: {
habitat: 'ocean'
tentacles: 8,
canChooseWorldCupWinners: true
},
owner: 1
}]
Upvotes: 1