I'm trying to create a many to many realtionship between the following object and I'd like to include an "is_active" boolean column on the relationship.
here are the objects:
Item.JS
module.exports = {
attributes: {
name: {
type: 'string'
},
description: {
type: 'string',
allowNull: true
},
categories: {
collection: 'category',
via: 'items',
},
}
}
Category.JS
module.exports = {
attributes: {
name: {
type: 'string'
},
description: {
type: 'string',
allowNull: true
},
items: {
collection: 'item',
via: 'categories',
},
}
}
How can I add the "is_active" boolean column and query by it and order to represent with relationship between item and category is active?
Thanks!
What you are looking for is a "through" model. Essentially, right now, you are using the automatically generated model (something like "item_categories" or "categories_item"). But, if you need to know more data about a relationship, you'll want to create a "through" model, where you can add whatever additional data you might need.
See the Sails.js docs here for more about the through associations.
The downside to this, according to the docs right now, is:
Currently, if you would like to add additional information to the through table, it will not be available when calling .populate. To do this you will need to query the through model manually.
So, you will have to manually query the ItemCategory
model manually to determine if it is active or not.
But, this is about what it looks like:
Item.js
module.exports = {
attributes: {
name: {
type: 'string'
},
description: {
type: 'string',
allowNull: true
},
categories: {
collection: 'category',
via: 'item',
through: 'itemcategory'
}
}
};
Categories.js
module.exports = {
attributes: {
name: {
type: 'string'
},
description: {
type: 'string',
allowNull: true
},
categories: {
collection: 'item',
via: 'category',
through: 'itemcategory'
}
}
};
ItemCategory.js
module.exports = {
attributes: {
item: {
model: 'item'
},
category: {
model: 'category'
},
isActive: {
type: 'bool'
}
}
};