I m new to loopback so don't know how to solve this kind of situations suppose I have model sale and model stock here is my code
Sales.beforeRemote('create', function (ctx, user, next) {
var stock=app.models.estshopinventory
var value= stock.find({where: {product_id:1}})// is this possible to assign value which got from stock
});
if users sale tv which price is 1000 and quantity 1 then it searches in stock table & if it found (productname) tv in stock then it does some calculations suppose data in stock before calculation like
productname | quantity | price
tv | 1 | 1000
after calculation (stock table)
productname | quantity | price
tv | 1 | 1000
how I can do this thing in loopback because I haven't found anything on google related to this kind of problem note I don't want to use multiple api or is there any other method to achieve this
As far as I can tell, you want to find whether or not the product which is about to be sold (marked by an entry in the sales model), exists in the stock or not. If it does, then the product related info registered in the stock gets modified and lets say the number available products drops by one. Below is a solution I whipped out, but haven't really tested it throughly.
Sample code:
module.exports = function(Sales) {
Sales.beforeRemote('create', function(ctx, data, next) {
let Stock = app.models.Stock;
let soldPieces = ctx.args.data.soldPieces;
let stockInstance = Stock.findOne({
where: {productName: ctx.args.data.productName},
})
let productData = Stock.update(
{"productName": ctx.args.data.productName},
{
"availablePieces": stockInstance.availablePieces - soldPieces,
}
);
next(); //Make sure to call it because such function are asynchronous
});
};
sales.json
{
"name": "Sales",
"plural": "Sales",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"productName": {
"type": "string",
"required": true
},
"productPrice": {
"type": "string"
},
"soldPieces": {
"type": "number"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
stock.json
{
"name": "Sales",
"plural": "Sales",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"productName": {
"type": "string",
"required": true
},
"productPrice": {
"type": "string"
},
"soldPieces": {
"type": "number"
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}
Further Reading: