I have two models:
Order.js
module.exports = {
attributes: {
//Id is generated by mongo and is a primary key
address: {
type: 'string',
required: true,
size: 1000
},
status: {
type: 'string',
required: true,
size: 15,
defaultsTo: 'pending',
enum: ['pending', 'processing', 'cancelled']
},
total: {
type: 'string',
required: true,
size: 50
},
menues: {
collection: 'menu',
via: 'orders',
dominant: true
},
customer: {
model: 'customer'
}
}
};
and Menu.js
module.exports = {
attributes: {
//Id is generated by mongo
name: {
type: 'string',
required: true,
size: 255
},
description: {
type: 'string',
required: true,
size: 1000
},
price: {
type: 'string',
required: true,
size: 15
},
picture: {
type: 'string',
size: 255
},
//Relations
orders: {
collection: 'order',
via: 'menues'
}
}
};
There is a many-to-many relation it perfectly works and creates a menu_orders__order_menues collection, everything is fine.
But I need to save quantity for each Menu in order. Like for menu id "1" quantity is 2 etc.
So an additional data is quantity: each order should have a definite amount of each menu.
What is the best way to do this, and were and how to store it in db? I thought to store it in relations table somehow, but I didn't fing how.
Please let me know the most correct and acceptable solution.
P.S. I currently use sails-mongo but will migrate to MySQL or Postgres soon so I need this to be done relative way.
Add quantity
field to your Menu model schema and can use afterCreate
function to set a value for it.
Order.js
module.exports = {
attributes: {
address: {
type: 'string',
required: true,
size: 1000
},
status: {
type: 'string',
required: true,
size: 15,
defaultsTo: 'pending',
enum: ['pending', 'processing', 'cancelled']
},
total: {
type: 'string',
required: true,
size: 50
},
menues: {
collection: 'menu',
via: 'orders',
dominant: true
},
customer: {
model: 'customer'
}
},
afterCreate: function (order, cb) {
Menu.find(order.menues, function (err, menues) {
if (err) return cb(err);
async.each(menues, function (menu, next) {
menu.quantity++;
menu.save(next);
}, cb);
});
}
};
Menu.js
module.exports = {
attributes: {
name: {
type: 'string',
required: true,
size: 255
},
description: {
type: 'string',
required: true,
size: 1000
},
price: {
type: 'string',
required: true,
size: 15
},
picture: {
type: 'string',
size: 255
},
quantity: {
type: 'number',
defaultsTo: 0
},
orders: {
collection: 'order',
via: 'menues'
}
}
};
It is not a finished solution. You have to handle afterUpdate
and afterDestroy
functions too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With